JAVA 根据模板生成doc文件

JAVA 根据模板生成doc文件

需求

根据模板生成对应的doc文档,文档内容动态填充。

实现

1.将doc模板转换为ftl文件,放入项目中
1.1 首先将模板另存为xml文件
1.2 更改xml文件后缀为ftl,即可把doc转为ftl.
2.代码实现
2.1 首先根据自身需求获取文档动态内容的数据,由于业务不同,这里不做过多阐述,我这里数据的返回类型为MAP.
2.2 通过调用方法,生成文档并通过浏览器下载

public static void WordExport(Map dataMap) throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    String eventId = "测试文档-" + dataMap.get("tasknum");

    //Configuration用于读取ftl文件
    Configuration configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
    //指定路径
    String templateFolder = NotTrueWorkOrderDocAction.class.getClassLoader().getResource("../../").getPath() + "templates/";
    configuration.setDirectoryForTemplateLoading(new File(templateFolder));
    // 输出文档路径及名称
    File outFile = new File(templateFolder + eventId + ".doc");

    //以 utf-8 的编码读取ftl文件
    Template t = null;
    //自己生成的ftl文件
    t = configuration.getTemplate("nottrueworkorder.ftl", "utf-8");
    Writer out = null;
    out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
    try {
        t.process(dataMap, out);
    } catch (TemplateException e) {
        e.printStackTrace();
    }
    out.close();

    InputStream fin = null;
    ServletOutputStream download = null;
    try {
        fin = new FileInputStream(outFile);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        // 设置浏览器以下载的方式处理该文件名
        String FileName = eventId + ".doc";
        response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(FileName, "UTF-8"))));
        download = response.getOutputStream();
        IOUtils.copy(fin, download);
        download.flush();
        fin.close();
    } finally {
        if (fin != null) {
            fin.close();
            if (download != null) {
                download.close();
            }
            if (outFile != null) {
                outFile.delete(); // 删除临时文件
            }
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值