Java使用freemarker导出Word

导入freemarker依赖

	<dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>

完成Word导出模版

  1. 新建word文档。
    在这里插入图片描述
  2. 将word文档另存为xml文件。(不能直接修改扩展名)
  3. 将xml文件的扩展名改为ftl

后台代码部分

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.*;

public class ToWord {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap();
        //map中的key要与${}中一样
        map.put("name","尼古拉斯赵四");
        map.put("phone","123456789");
        map.put("birth","2020年11月24日");
        map.put("sex","男");
        map.put("age","3");
        //用于读取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            //指定ftl文件路径
            configuration.setDirectoryForTemplateLoading(new File("G:/"));
            //输出文件的路径
            File outFile = new File("G:/test.doc");
            Template t =  configuration.getTemplate("test.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            try {
                t.process(map, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

效果展示

在这里插入图片描述

可能出现的异常

在这里插入图片描述

解决方法:

  • 再次将word文档另存为xml文件,然后修改xml后缀为ftl。
  • 若还是出现该异常,则使用记事本等工具打开xml文件,检查每个${},很有可能在word文档转xml时出现了问题。
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值