1.引入依赖
<!--导出doc模板工具-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.6</version>
</dependency>
2.编码
/**
* 导出doc文件
* @param id
* @return
*/
@GetMapping("/exportDoc/{id}")
public void exportDoc(@PathVariable String id,HttpServletResponse response) {
Task taskById = taskService.getTaskById(id);
Map<String,String> map=new HashMap<>();
map.put("title",taskById.getTitle());
map.put("year",String.valueOf(taskById.getYear()));
map.put("taskCode",taskById.getTaskCode());
map.put("workDemand",taskById.getWorkDemand());
map.put("creatorName",taskById.getCreatorName());
map.put("createdTime", DateUtil.format(taskById.getCreatedTime(), "yyyy-MM-dd HH:mm:ss"));
map.put("responsibleDepartmentName",taskById.getResponsibleDepartmentName());
map.put("responsiblePerson",taskById.getResponsiblePerson());
map.put("supervisionPerson",taskById.getSupervisionPerson());
map.put("limitDate",DateUtil.format(taskById.getLimitDate(), "yyyy-MM-dd HH:mm:ss"));
map.put("startDate",DateUtil.format(taskById.getStartDate(), "yyyy-MM-dd HH:mm:ss"));
map.put("endDate",DateUtil.format(taskById.getEndDate(), "yyyy-MM-dd HH:mm:ss"));
ClassPathResource resource = new ClassPathResource("poiTemplate/taskDocTemplate.docx");
XWPFTemplate template = XWPFTemplate.compile(resource.getStream()).render(
map);
/*try {
template.write(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\鸭河\\output.docx"));
} catch (IOException e) {
e.printStackTrace();
}*/
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");
try {
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
} catch (IOException e) {
e.printStackTrace();
}
}