版本
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>
模板
需要填充的内容通过{{}},格式可以直接在模板上直接编辑好,导出之后格式会保留,导出列表的需要在加多一点处理。{{lists}}对应工具类的lists
工具类
生成word的工具类
public class EditWordUtil {
public static boolean createWord(String fileName, InputStream templatePath, Map dates, HttpServletResponse response) throws IOException {
//setContentType:设置响应内容类型。
response.setContentType("application/msword");
//setCharacterEncoding:设置字符集。
response.setCharacterEncoding("utf-8");
//设置表名
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
// 读取模板templatePath并将paramMap的内容填充进模板,即编辑模板+渲染数据
XWPFTemplate template = XWPFTemplate.compile(templatePath).render(dates);
try {
// 将填充之后的模板写入filePath
template.write(bos);
template.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
out.flush();
bos.flush();
return true;
}
public static boolean createWordOfList(String fileName, InputStream templatePath, Map dates, HttpServletResponse response) throws IOException {
//setContentType:设置响应内容类型。这表示是一个pdf文件
response.setContentType("application/msword");
//setCharacterEncoding:设置字符集。
response.setCharacterEncoding("utf-8");
//设置表名
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();
Configure configure = Configure.builder().bind("lists", loopRowTableRenderPolicy).build();
// 读取模板templatePath并将paramMap的内容填充进模板,即编辑模板+渲染数据
XWPFTemplate template = XWPFTemplate.compile(templatePath,configure).render(dates);
try {
// 将填充之后的模板写入filePath
template.write(bos);
template.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
out.flush();
bos.flush();
return true;
}
}
处理层
通过map将所需的数据写入
//获取数据
ReportPo reportPo = service.getById(id);
List<xxx> list = service.list(xxx);
//获取模板
InputStream resourceAsStream = this.getClass().getResourceAsStream("模板路径");
填充数据
Map<String, Object> map = new HashMap<>();
map.put("claimLaunchReportTitle",claimLaunchReportTitle);
map.put("claimReason",reportPo.getClaimReason());
map.put("claimContent",reportPo.getClaimContent());
map.put("claimRely",reportPo.getClaimRely());
map.put("claimFee",reportPo.getClaimFee());
map.put("claimPrinciple",reportPo.getClaimPrinciple());
map.put("otherContent",reportPo.getOtherContent());
map.put("lists",list);
EditWordUtil.createWordOfList(sb.toString(),resourceAsStream,map,response);
response.flushBuffer();
resourceAsStream.close();
谨记关闭流!!!