freemarker 生成word

2023-07-12,,

一、生成模板,动态获取的部分用${变量名},然后将word另存为xml文件,再将后缀名改成ftl格式。然后将模板放在对应的目录下。

二、引入freemarker包,mawen引用

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

三、代码实现

@ApiOperation(value = "word", httpMethod = "GET")
@RequestMapping(value = "/word", method = RequestMethod.GET)
@Transactional
public void getWord(HttpServletResponse response)
{
try {
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("id", 123456);
dataMap.put("code", "张三");
dataMap.put("name", "123123");
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//指定模板路径的第二种方式,我的路径是D:/ 还有其他方式
configuration.setDirectoryForTemplateLoading(new File("D:/"));//这里对应模板的物理路径 // 输出文档路径及名称
// File outFile = new File("D:/test.doc");
//以utf-8的编码读取ftl文件
Template t = configuration.getTemplate("模板1.ftl","utf-8");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("适得府君书的", "UTF-8") + ".doc");
// Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
Writer out = null;
out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
t.process(dataMap, out);
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

我生成的模板:

word导出的结果:

对应map中的三个值。

freemarker 生成word的相关教程结束。

《freemarker 生成word.doc》

下载本文的Word格式文档,以方便收藏与打印。