背景
最近有一个需求是需要动态导出合同、订单等信息,导出一个word文档供客户进行下载查看。
需要导出的word文件,主要可以分为两种类型。
-
导出固定内容和图片的word文档 -
导出表格内容不固定的word文档
经过对比工具,我实践过两种实现方式。第一种是FreeMarker模板来进行填充;第二种就是文中介绍的POI-TL。
这里我推荐使用POI-TL。
介绍
POI-TL是word模板引擎,基于Apache POI,提供更友好的API。
目前最新的版本是1.12.X,POI对应版本是5.2.2。
这里需要注意的是POI和POI-TL有一个对应的关系。
准备工作
我使用的POI-TL版本是1.10.0
@RequestMapping("dynamicTable")
public void dynamicTable(HttpServletResponse response) {
//1.组装数据
StudentTable table = assertData();
//2.获取根目录,创建模板文件
String path = copyTempFile("word/2.docx");
//3.获取临时文件
String fileName = System.currentTimeMillis() + ".docx";
String tmpPath = "D:\" + fileName;
try {
//4.编译模板,渲染数据
LoopRowTableRenderPolicy hackLoopTableRenderPolicy = new LoopRowTableRenderPolicy();
Configure config =
Configure.builder().bind("studentList", hackLoopTableRenderPolicy).bind("studentList1", hackLoopTableRenderPolicy).build();
XWPFTemplate template = XWPFTemplate.compile(path, config).render(table);
//5.写入到指定目录位置
FileOutputStream fos = new FileOutputStream(tmpPath);
template.write(fos);
fos.flush();
fos.close();
template.close();
//6.提供下载
down(response, tmpPath, fileName);
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.删除临时文件
File file = new File(tmpPath);
file.delete();
File copyFile = new File(path);
copyFile.delete();
}
}
测试
请求接口:http://127.0.0.1:1000/file/dynamicTable
效果如下:
本篇文章来源于微信公众号: ssw在路上的蚂蚁
微信扫描下方的二维码阅读本文
Comments NOTHING