注释:由于poi-tl对循环列表的导出说明的不是很详细,故此处导出时使用poi和poi-tl结合导出。
基本思路为:使用poi导出文本和列表,存为临时文件,再以临时文件为模板,使用poi-tl导出图表,最终生成导出结果。
应注意把临时文件删除
@ApiOperation(value = "项目报告导出")
@ResponseBody
@GetMapping("/docx/{id}")
public Object wordExporttest2(@PathVariable Integer id,HttpServletResponse re) throws Exception {
Map<String,Object> infos = service.docxInfos(id);
Map<String,List<Map<String,Object>>> infolist = new HashMap<>();
infolist.put("tool", service.toolInfos(id));
infolist.put("ruleset", service.rulesetInfos(id));
infolist.put("build", service.buildInfos(id));
infolist.put("qg", service.qualityGateInfos(id));
infolist.put("sf", service.sourcefileInfos(id));
infolist.put("sr", service.fileMetricInfos(id));
infolist.put("issue", service.issueInfos(id));
// FileInputStream in = new FileInputStream("C:\\Users\\Desktop\\e2\\模板 .docx");
WordDocxWriter docx = new WordDocxWriter(
// in);
ProjectExportController.class.getResourceAsStream("/static/template/projectExportTemplate.docx"));
docx.setMarker(infos).setMarkers(infolist);
byte[] bytes = docx.getBytes();
File tmp = CstDirs.getDir(CstDir.tmp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
File xdoc = new File(tmp,id+sdf.format(new Date())+".docx");
FileOutputStream fos = new FileOutputStream(xdoc);
fos.write(bytes);
fos.close();
Map<String,Object> plinfos = new HashMap<>();
String name = "";
if(service.getById(id) != null) {
name = StringKit.of(service.getById(id).getName());
}
plinfos.put("page", name+" 文件");
plinfos.put("severityPie", service.issueServerityPie(id));
plinfos.put("unFixedPie", service.unFixedIssueServerityPie(id));
plinfos.put("statePie", service.issueStatePie(id));
plinfos.put("statusPie", service.issueStatusPie(id));
plinfos.put("ruleCodeBar", service.issueRuleTop10(id));
plinfos.put("buildLine", service.BuildLineTop10(id));
plinfos.put("ownerBar", service.issueOwnerTop10(id));
plinfos.put("sourcefileBar", service.issueSourcefileTop10(id));
XWPFTemplate template = XWPFTemplate.compile(xdoc).render(plinfos);
xdoc.delete();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
template.write(baos);
template.close();
// baos.close();
// 设置http协议头部
HttpHeaders headers = new HttpHeaders();
// 设置文件名
String fileName = "";
fileName = new String((service.getById(id).getName() + "项目报告.docx").getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
re.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
return baos.toByteArray();
}