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包即可实现这个功能.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值