想获得如下word
需创建一份类似于该word,但是需要替换的内容需要用约定的字符串替换,如
接下来调用下载方法
单个word下载方法
private void wordPrintf(HttpServletResponse response,Map<String, Object> data) throws IOException {
//单个下载 返回单个文件
String fileName = DateUtil.format(new Date(), "yyyyMMddHH") + QCC__WORD ;
//表格插入
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
//绑定列表,里面的替换字符串为表单的key。
ConfigureBuilder configureBuilder = Configure.builder()
.bind("activityPlan", policy)
.bind("countermeasure",policy);
Configure config = configureBuilder.build();
//获取模板文件路径
ClassPathResource resource = new ClassPathResource(QCC_TEMPLATE_WORD_DOCX);
XWPFTemplate template = null;
try {
template = XWPFTemplate.compile(resource.getInputStream(), config).render(data);
FileUtils.setAttachmentResponseHeader(response, fileName);
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(out);
bos.flush();
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally {
if(template != null){
try {
template.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
若word中有表单
上面的代码中也要加上表单的key,表单中list的内容用 [] 中括号。
data中与上面替换的字符串格式是
之后压缩包的方法是
//多个下载 返回压缩包
//进行导出下载
String zipName = "服务接口文档下载" + DateUtils.dateToStr(new Date(), CommonConstant.YYYYMMDDHHMMSS) + ".zip";
FileUtils.setAttachmentResponseHeader(response, zipName);
ClassPathResource resource = new ClassPathResource(CommonConstant.DATA_PUSH_DOCUMENT_TEMPLATE_ROOT);
try (ZipOutputStream out = new ZipOutputStream(response.getOutputStream())) {
for (GHAImDataPushServiceManagement serviceManagement : serviceManagementList) {
GHAImDataPushServiceDocumentViewVO serviceDocumentViewVO = this.serviceDocumentView(serviceManagement.getServiceId());
ZipEntry entry = new ZipEntry(serviceDocumentViewVO.getServiceName() + "接口文档" + DateUtils.dateToStr(new Date(),
CommonConstant.YYYYMMDDHHMMSS) + ".docx");
out.putNextEntry(entry);
//表格插入
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
//绑定列表
ConfigureBuilder configureBuilder = Configure.builder()
.bind("headers", policy)
.bind("bodyRequestParamList",policy)
.bind("requestResponseParamList", policy);
Configure config = configureBuilder.build();
XWPFTemplate template = null;
try {
template = XWPFTemplate.compile(resource.getInputStream(), config).render(serviceDocumentViewVO);
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(out);
bos.flush();
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally {
if(template != null){
try {
template.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
out.closeEntry();
}
} catch (Exception e) {
LOGGER.error("服务接口文档下载失败:{}", ExceptionUtil.getExceptionMessage(e));
throw e;
}