java 利用 poi-tl 导出 word
导出模板
图片处理
details是要遍历的表格里得数据,图片支持多张
List<InfViolationDetail> details = infViolationDetailService.selectList(search);
// 输出的图片对象列表
List<PictureRenderData> imgList = null;
if (!CollectionUtils.isEmpty(details)) {
for (int i = 1; i <= details.size(); i++) {
details.get(i-1).setId(Long.valueOf(i));
String violationImg = details.get(i-1).getViolationImg();
// 输出的图片对象列表
imgList = new ArrayList<>();
if (StringUtil.isNotBlank(violationImg)) {
violationImg = ","+violationImg;
String []urlStrs = violationImg.split(",");
for (int j = 0; j < urlStrs.length; j++) {
String url = platformUrl+urlStrs[j];
PictureRenderData picItem = Pictures.ofUrl(url).size( 60, 50) .center().create();
imgList.add(picItem);
}
}
details.get(i-1).setImgList(imgList);
}
}
获取模板,绑定模板里得内容
InputStream resourceAsStream = ResourceReader.class.getClassLoader().getResourceAsStream("导出模板.docx");
Map<String, Object> datas = new HashMap<String, Object>() {
{
put("details", details);
put("violationStartPosition",infViolation.getViolationStartPosition());
put("violationTime",DateUtils.dateToc(infViolation.getViolationTime()));
put("ext1",infViolation.getExt1());
put("ext19",infViolation.getExt19());
put("ext15",infViolation.getExt15());
put("ext20",infViolation.getExt20());
put("inspector",infViolation.getInspector());
put("ext21",infViolation.getExt21());
put("punishmentSituation",infViolation.getPunishmentSituation());
put("ext27",infViolation.getExt27());
put("ext28",infViolation.getExt28());
put("sgEnterName",infViolation.getSgEnterName());
}
};
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
Configure config = Configure.builder()
.bind("details", policy).build();
XWPFTemplate template = XWPFTemplate.compile(resourceAsStream,config).render(datas);
Map<String, Object> map = new HashMap<>();
map.put("template", template);
map.put("fileName", infViolation.getViolationStartPosition());
return map;
输出word
protected void buildWordDocument(String fileName, XWPFTemplate document, HttpServletResponse response) throws Exception {
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream os = response.getOutputStream();
document.write(os);
os.close();
}