第一步:导入依赖
<!--生成word文档-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.3</version>
</dependency>
<!--数字转为汉字大写-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
第二步:业务代码
@Override
public void downloadEngineeringWord(HttpServletResponse response, Long engineeringId) {
String engineeringWordSql = "你的查询sql";
Map<String, Object> tendersWord = (Map<String, Object>) SqlUtil.getMapToList(engineeringWordSql, entityManager).get(0);
if (ObjectUtils.isEmpty(tendersWord)) {
return;
}
//判断文本是否出现
if (tendersWord.containsKey("margin") && !ObjectUtils.isEmpty(tendersWord.get("margin"))) {
BigDecimal price = (BigDecimal) tendersWord.get("margin");
tendersWord.put("marginShow", price.signum() > 0);
} else {
tendersWord.put("marginShow", false);
}
//将数字金额转为汉字大写
if (tendersWord.containsKey("maxPrice") && !ObjectUtils.isEmpty(tendersWord.get("maxPrice"))) {
double money = Double.parseDouble(tendersWord.get("maxPrice").toString());
String chineseMoney = NumberChineseFormatter.format(money, true, true);
tendersWord.put("highestPrice", chineseMoney);
}
//对前端使用\n换行的段落文本进行格式化换行
Object qualifications = tendersWord.get("qualifications");
if (!ObjectUtils.isEmpty(qualifications) && qualifications.toString().contains("/")) {
List<String> qualificationsList = Arrays.asList(qualifications.toString().split("/"));
List<Map<String, Object>> qualificationMapList = new ArrayList<>();
qualificationsList.stream().filter(f -> !ObjectUtils.isEmpty(f.trim())).forEach(qualification -> {
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("qualification", qualification);
qualificationMapList.add(itemMap);
});
tendersWord.put("qualifications", qualificationMapList);
}
String fileName = "工程文件";
try {
File wordTemplate = new File("start/src/main/resources/" + fileName + ".docx");
XWPFTemplate template = XWPFTemplate.compile(wordTemplate.getAbsolutePath()).render(tendersWord);
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".docx", "utf-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
} catch (IOException e) {
throw new BizException(fileName + ".docx 生成失败,请稍后再试!");
}
}
官网链接:Poi-tl Documentation