模板格式 
1.pom引入
-
Apache POI 4.1.2+
-
JDK 1.8+
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.1</version>
</dependency>
2.业务
1)controller
@GetMapping("/report")
@ApiOperation(value = "生产报告")
public void report(HttpServletResponse response){
try{
dataReportService.dataReport(response);
}catch (Exception e){
e.printStackTrace();
}
}
2)service
void dataReport(HttpServletResponse response);
3)serviceImpl
@Override
public void dataReport(HttpServletResponse response, String startTime, String endTime, String subCenterCode, String parentSubCenterCode) {
String path = docxPath+"template.docx";
//获取报告数据
JSONObject jsonObject = getReportData();
XWPFTemplate template = XWPFTemplate.compile(path).render(
new HashMap<String, Object>(){{
//取数据 然后put 和模板文件中{{}}内容一一对应
put("title", jsonObject.get("title"));
put("month",jsonObject.get("month"));
}});
OutputStream out = null;
BufferedOutputStream bos = null;
try {
response.setContentType("application/octet-stream");
SimpleDateFormat DateStr1 = new SimpleDateFormat("yyyy年MM月dd日");
String start = DateStr1.format(DateUtil.parseDate(startTime.substring(0, 10)));
String end = DateStr1.format(DateUtil.parseDate(endTime.substring(0, 10)));
String docxName = start+"-"+end;
System.out.println(docxName);
String fileName = "报告("+docxName+").docx";
response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
out = response.getOutputStream();
bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}