【Java】poi-tl 使用Word模板渲染动态表格

前言

poi-tl 是一个基于 Apache POI 和 FreeMarker 的 Java 模板引擎,可以用于动态生成 Word、Excel、PowerPoint 等文档。使用 poi-tl 可以方便地将数据填充到模板中,生成符合要求的文档。

poi-tl官方文档地址:http://deepoove.com/poi-tl/#_%E7%89%88%E6%9C%AC

先附上导出效果图:

在这里插入图片描述

1.创建word模板,并将模板放在resource文件夹下

这步建议手动创建,之前客服提供了一个pdf文件,我把它转成了word,用这个word当模板.结果意外发生了,动态表格数据不会自动分页,所有数据都挤在第一页…改模板,加分页符…都不好用,最后手动新建一个模板就好了…

数据结构:

代码中可以用对象封装,也可以用map.

区块对是 {{?innerList}} {{/innerList}},我想要的样式就是循环这部分内容

{{contestExcelList}} 是动态列表集合

外层out(对象) :date (字符串) innerList(集合)

inner 对象:

title1(字符串)

title2(字符串)

@image(图片)

contestExcelList(集合)-

contestExcel(对象):num(字符串)

projectName(字符串)

score(字符串)

在这里插入图片描述

2.引入依赖

       
            com.deepoove
            poi-tl
            1.10.0
        

  

            org.docx4j
            docx4j-JAXB-MOXy
            8.2.9
        
 
            org.docx4j
            docx4j-export-fo
            8.2.9
        

3.代码实现

public void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Map> innerMapList= new ArrayList();   //inner集合
 Map innerMap = new HashMap();             //inner对象
 
  List contestExcelList= new ArrayList();    //自己的动态表格数据
  for (int j = 0; j < 10; j++) {
        ContestExcel contestExcelEntity = new ContestExcel();
             contestExcelEntity.setNum(j+1);
             contestExcelEntity.setProjectName("项目名称");
             contestExcelEntity.setScore("99");
             contestExcelList.add(contestExcelEntity);
  }
  
  innerMap .put("title1", Texts.of("标题1").create());
  innerMap .put("title2", Texts.of("标题2").create());
  innerMap .put("image", Pictures.ofUrl("图片url链接");
  innerMap .put("contestExcelList", contestExcelList);   
  innerMapList.add(innerMap);
  
 Map outMap= new HashMap();  //外层out(对象)
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   outMap.put("innerList", innerMapList);
   outMap.put("date", sdf.format(date));

 String name = "打分表";
 String destFilePath = TestFileUtil.getPath();

//动态表格变量可以用[] 对应
 LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        //这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式
        Configure config = Configure.builder()
                .bind("contestExcelEntityList", policy).build();


//获取模板
InputStream inputStream = ClassUtils
                .getDefaultClassLoader()
                .getResourceAsStream("wordTemplate.docx");  //将模板放在resource文件夹下
//生成docx文件
XWPFTemplate compile = XWPFTemplate.compile(inputStream, config);
        compile.render(map);
        compile.writeToFile(destFilePath + name + ".docx");
        inputStream.close();

//转成pdf文件并导出
        outputMethod(response, toPdf2(destFilePath, name));

转pdf 和导出方法:

//转pdf方法

    public static String toPdf2(String destFilePath, String zipName) throws Exception {
        String destFilePath2 = "";
        char firstChar = destFilePath.charAt(0);
        if (firstChar == '/') {
            destFilePath2 = destFilePath.substring(1);
        } else {
            destFilePath2 = destFilePath;
        }
//此处代码 参考  https://editor.csdn.net/md/?articleId=133790383
        WordToPdfTest_Docx4j.wordToPdf(destFilePath2 + zipName + ".docx", destFilePath2 + zipName + ".pdf");
        return destFilePath2 + zipName + ".pdf";
    }

}

//导出方法
  public void outputMethod(HttpServletResponse response, String filePath) {

        ServletOutputStream out = null;
//        File file = new File("d:\\test\\result.pdf");
        File file = new File(filePath);
        FileInputStream inputStream = null;
        try {
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            if (filePath.contains(".xlsx")) {
                //
                /** 导出excel文件流 */
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                response.setCharacterEncoding("UTF-8");
            } else {

                /** 导出pdf文件流 */
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/pdf");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            }


            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("输入流关闭失败, {}", e);
            }
            try {
                out.close();
            } catch (IOException e) {
                logger.error("输出流关闭失败, {}", e);
            }
        }
        file.delete();//删除.xlsx  或    pdf文件
        if (filePath.contains(".pdf")) {  //如果是pdf ,还需要删除生成的docx
            File fileDocx = new File(filePath.substring(0, filePath.lastIndexOf(".")) + ".docx");
            fileDocx.delete();
        }

    }

4.前端blob导出参考:

https://editor.csdn.net/md/?articleId=133790129

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/4e67507a01.html