package bril.com.cn.poidemo;

import android.content.Context;
import android.os.Environment;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by sunny on 2018-1-1.
 */

public class PoiUtil {

    public static void exportWord(Context context,String path, String content)  {
        String templatePath = Environment
                .getExternalStorageDirectory().getPath() + "/documentocr/docs/demo.docx";
        InputStream is = null;
        HWPFDocument doc = null;
        try {
            is = new FileInputStream(templatePath);
            doc = new HWPFDocument(is);
            Range range = doc.getRange();
            //把range范围内的${reportDate}替换为当前的日期
            range.replaceText("${time}", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            range.replaceText("${title}", "检务通识别文档");
            range.replaceText("${content}", content);
            OutputStream os = new FileOutputStream(path);
            //把doc输出到输出流中
            doc.write(os);
            closeStream(os);
            closeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭输入流
     * @param is
     */
    private static void closeStream(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     * @param os
     */
    private static void closeStream(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
