java IO 基于模板文件替换字符生成word文档

有很多人会选择用POI来实现这个功能,虽然说POI第三方包提供了很多方法,但JAVA IO流也不是吃素的,同样也可以实现基于模板文件替换字符生成文档.
这个功能在web应用中还是蛮常见的,用户们喜欢根据自己的模板,然后在加上提供的内容,自动生成出不同的word文档,省时省力.现在直接贴出代码.

public class WangTest {

    public static void main(String[] args) {

        String templateContent = null;
        String filePath = "D:/newWorkSpace20160516/SCPT/WebRoot/template/wangtest.mht";//模版文件
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
        }
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);// 用来存装读取到的内容
        byte[] temp = new byte[1024];
        int size = 0;
        try {
            while ((size = in.read(temp)) != -1) {
                baos.write(temp, 0, size);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        templateContent = baos.toString();
        String content = templateContent;
        /**
         * 直接使用String的replace直接替换文档中的占位符,这里写死,同样可以以参数形式传入
         */
        content = content.replace("${name}", "wangzaogen" + "");
        content = content.replace("${sex}", "男" + "");
        content = content.replace("${age}", "20" + "");
        File wordFile = new File(
                "D:/newWorkSpace20160516/SCPT/WebRoot/template/+" + 2018
                        + "wangtest.doc");//转换后的word文档
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(wordFile, true);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException e) {
        }
    }
}

这里的模板文件是以.mht结尾的文件,不要大惊小怪的,这是由word文档另存为的网页文件
这里写图片描述
简单的模板内容如下图:
这里写图片描述
执行main方法后转换的word文档后:
这里写图片描述
很简单的一段代码,不用引用第三方的jar包即可实现这个功能.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章