1. 引入maven依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.5</version>
</dependency>
如果系统中引用了其他poi组件,要注意不同版本的对应关系,1.10.5版本的poi-tl要求Apache POI4.1.2,JDK1.8+。如果你的项目引用了低版本可能会导致出现NoSuchMethodError 、ClassNotFoundException 、NoClassDefFoundError异常。
2.代码示例
Map<String, Object> dataModel = new HashMap<>();
//获取需要插入的文档附件
List<ReqFileDO> sampleDocument = fileApi.getFile("样品管理-文件", sampleRespVO.getId());
List<Map<String, Object>> sampleDocumentList = new ArrayList<>();
for (ReqFileDO reqFileDO : sampleDocument) {
//判断文件类型
String extName = FileNameUtil.extName(reqFileDO.getName());
AttachmentType attachmentType = null;
if ("docx".equals(extName)) {
attachmentType = AttachmentType.DOCX;
} else if ("xlsx".equals(extName)) {
attachmentType = AttachmentType.XLSX;
}
if (attachmentType != null) {
Map<String, Object> map1 = new HashMap<>();
byte[] fileContent = fileApi.getFileContent(String.valueOf(reqFileDO.getId()));
AttachmentRenderData attach = Attachments.ofBytes(fileContent,attachmentType).create();
map1.put("fileName",reqFileDO.getName());
map1.put("attach",attach);
sampleDocumentList.add(map1);
}
}
dataModel.put("sampleDocument",sampleDocumentList);
Configure config = Configure.builder()
//将附件插件注册为新标签类型 使用{{%var}}
.addPlugin('%', new AttachmentRenderPolicy())
.build();
//进行报告生成 获取报告模板内容
byte[] template = fileApi.getFileContent(reportTemplate.getTemplateFileId());
XWPFTemplate xwpfTemplate = XWPFTemplate.compile( new ByteArrayInputStream(template),config).render(dataModel);
ByteArrayOutputStream out = new ByteArrayOutputStream();
xwpfTemplate.write(out);
out.close();
xwpfTemplate.close();
//获取后缀
String extName = FileNameUtil.extName("模板文档.docx");
//生成文件并存储文件信息
ReqFileDO file = fileApi.createFile("文件名称示例" + '.' + extName, out.toByteArray(), 1L, "报告管理—项目报告", taskReport.getId());
文档使用示例
template.docx
{{?sampleDocument}}
{{%attach}}
{{fileName}}
{{/sampleDocument}}