1.poi-tl简介
poi-tl是一个基于Apache POI的Word模板引擎,也是一个免费开源的Java类库(官方文档: Poi-tl Documentation)
2.poi-tl特性
1.支持注入的模板类型
-
文本
-
图片
-
列表
-
区块对
-
嵌套
-
多系列图表
-
单系列图表
-
组合图表
2.poi-tl使用步骤
1.引入依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.0</version>
</dependency>
2.核心使用代码
XWPFTemplate template = XWPFTemplate.compile("template.docx").render(
new HashMap<String, Object>(){
{
put("title", "Hi, YC");
}});
template.writeAndClose(new FileOutputStream("output.docx"));
3.常用方法
XWPFTemplate template = XWPFTemplate.compile("filePath"); // 编译模板
template.render(填充的数据map或对象) //渲染数据
template.write(输出流out) //输出到流
4.具体实现
1.构建word模板
模板中填充位置占位符语法: { {name}}
2.引入模板
XWPFTemplate template = XWPFTemplate.compile("filePath")
3.模板中填充数据类型
3.1 Map: 键为占位符名称, 值为填充的具体数据
3.2 对象: 对象中的属性为占位符名称
4.构建word文件并导出
// 数据转换
Map<String, Object> fillMap = new HashMap<>();
// 文件名称
String fileName = URLEncoder.encode("文件名称", StandardCharsets.UTF_8);
// 指示响应内容的格式
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".docx");
try (OutputStream out = response.getOutputStream();
XWPFTemplate template = getTemplate(filePath)) {
// 数据填充
template.render(fillMap);
template.write(out);
out.flush();
} catch (IOException ex) {
throw new IOException(ex);
}