java打印/导出自定义word文档

因为采用的替换,所以word模板对应的空格必须与导出实体类的变量名/键名对应

在这里插入图片描述

  @Resource
  PoiUtils poiUtils;
  @Autowired
  HttpServletResponse response;
public R writeDoc(String token, String id){
      Map map = new HashMap<>();
	map.put("recvUnitName", m.get("recvUnitName"));
	 map.put("limitTime", m.get("limitTime"));
	map.put("currentDate", DateUtils.format(new Date(),DATE_PATTERN));
	String templateFile="export.doc";//模板文档  路径main/resource/export.doc
	poiUtils.getBuild(templateFile, map, response); //调用方法 ,  参数模板名称,内容(实体对象),响应对象
	return R.ok();
}
@Component
public class PoiUtils {
//tmpFile   模板路径
//contentMap   导出内容
public void getBuild(String tmpFile, Map contentMap, HttpServletResponse response) {
    InputStream inputStream = PoiUtils.class.getClassLoader().getResourceAsStream(tmpFile);
    HWPFDocument document = null;
    try {
      document = new HWPFDocument(inputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 读取文本内容
    assert document != null;
    Range bodyRange = document.getRange();
    // 替换内容,   
    for (Map.Entry entry : contentMap.entrySet()) {
      String value = entry.getValue();
      bodyRange.replaceText("${" + entry.getKey() + "}", Objects.nonNull(value) ? value : "");
    }

    String fileName = contentMap.getOrDefault("code", "");
    String title = contentMap.getOrDefault("title", "");
    if (StringUtils.isNotBlank(title)) {
      fileName += "-" + title;
    }

    fileName += ".doc";

    //导出到文件
    try {
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/msword");
      response.setHeader("Content-Disposition", "attachment;filename="
          .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
      OutputStream out = response.getOutputStream();
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      document.write(byteArrayOutputStream);
      out.write(byteArrayOutputStream.toByteArray());
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

你可能感兴趣的:(java,servlet)