pot-tl动态遍历

最近工作需要导出word文档,选择使用了poi-tl这个word模板引擎
官网文档 Poi-tl Documentation

在使用过程中需要动态遍历一个集合数据,可以使用ListRenderPolicy这个插件,但是官方文档不知为何没有写出具体实例,但是在源码里是可以找到的相应的实例
源码地址

这里我自己写个测试实例以作记录

  • 具体代码:

    @Data
    public class WordVO {
        private List<PictureRenderData> picture;
    
        private String problem;
    
        private String reason;
    }
    
    @RestController
    public class TestController {
    
      @GetMapping("/download")
      public void download() throws IOException {
          Map<String, Object> map = new HashMap<String, Object>();
          InputStream inputStream = Thread.currentThread().getContextClassLoader()
                  .getResourceAsStream("template/test.docx");
          ListRenderPolicy policy = new ListRenderPolicy();
          Configure config = Configure.newBuilder()
                  .bind("pictures", policy).build();
          List<WordVO> detailList = new ArrayList<>();
          WordVO one = new WordVO();
          WordVO two = new WordVO();
          one.setProblem("问题测试1");
          two.setProblem("问题测试2");
          one.setReason("原因测试1");
          two.setReason("原因测试2");
          List<PictureRenderData> pList1 = new ArrayList<>();
          List<PictureRenderData> pList2 = new ArrayList<>();
          pList1.add(new PictureRenderData(100, 120, "C:/Users/gp/Desktop/1.jpg"));
          pList1.add(new PictureRenderData(100, 120, "C:/Users/gp/Desktop/2.jpg"));
          pList2.add(new PictureRenderData(100, 120, "C:/Users/gp/Desktop/1.jpg"));
          one.setPicture(pList1);
          two.setPicture(pList2);
          detailList.add(one);
          detailList.add(two);
          List<Object> list = new ArrayList<>();
          detailList.forEach(wordVO -> {
              list.add(new TextRenderData(wordVO.getProblem()));
              list.add(new TextRenderData(wordVO.getReason()));
              if (CollectionUtils.isNotEmpty(wordVO.getPicture())) {
                  list.addAll(wordVO.getPicture());
              }
          });
          map.put("pictures", list);
          XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(map);
          template.writeToFile("C:/Users/gp/Desktop/测试.docx");
      }
    }
    
  • word模板
    pot-tl动态遍历_第1张图片

  • 导出结果
    pot-tl动态遍历_第2张图片

你可能感兴趣的:(工作总结)