使用FreeMarker生成word文档

时间:2023-03-09 20:11:06
使用FreeMarker生成word文档

生成word文档的框架比较多,比如poi,java2word,itext和freemarker。 调研之后,freemarker来实现挺简单的,具体步骤如下:

1. 新建word文档,占位符用${},比如:${name}。样例:

你好 ${name}

2. 把word另存为xml文件,如:example.xml

3. 修改文件格式,把example.xml改为example.ftl.

4.安装notePad++ xml tools插件,用来打开example.ftl文件。里面可能有些文件分成了好几行,需要合并成一行,适当调整。

5. 用freemarker解析ftl文件,并填充占位符:

public static byte[] generateWord() {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
configuration.setDefaultEncoding(UTF8);
configuration.setClassForTemplateLoading(WordUtil.class, "/templates-path/"); //模板文件的路径
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Template template = configuration.getTemplate("example.ftl", UTF8);
Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF8));
    Map<String, Object> dataMap = new HashMap<String,Object>();
    dataMap.put("name","jacky"); template.process(dataMap, writer);
    } catch (TemplateException | IOException e) {
log.error(e.getMessage(), e);
}
return out.toByteArray();
}