1.pom文件
```java
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>```
<!-- EasyPoi依赖 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.0</version>
</dependency>
2.代码实现
@ApiOperation(value = "easypoi导出(模板)ftl转doc")
@GetMapping("/export3")
public void export3(HttpServletResponse response) {
Map<String, Object> res = new HashMap<>();
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 12; i++) {
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "张三" + i);
map2.put("sex", "男");
map2.put("age", i + "岁");
map2.put("address", "西安市");
list.add(map2);
}
// datas必须和flt文件<#list>标签中的名称一样
res.put("datas", list);
PrintWriter out = null;
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File("E:\\codeWork\\hmall\\item-service\\src\\main\\resources\\docx")); // 模版文件前缀路径
String fileName = "测试文档2.doc";
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("20240828.ftl", "utf-8"); // 模版名称
response.reset();
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("GBK"), "iso8859-1") + "\"");
response.setCharacterEncoding("utf-8");//此句非常关键,不然word文档全是乱码
out = response.getWriter();
template.process(res, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
out.close();
}
}
}
3. 结果
注意 :
word转xml(ftl)的时候,一定要用xml格式化,不要直接用idea的代码格式化,如果下载的文件有大小,但是打开没东西,则将文件改为xml双击打开,会有具体的报错行数,看缺失的标签的。