poi-tl动态遍历
Posted 听风者-better
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poi-tl动态遍历相关的知识,希望对你有一定的参考价值。
最近工作需要导出word文档,选择使用了poi-tl这个word模板引擎
官网文档 Poi-tl Documentation
在使用过程中需要动态遍历一个集合数据,可以使用ListRenderPolicy这个插件,但是官方文档不知为何没有写出具体实例,但是在源码里是可以找到的相应的实例
源码地址
这里我自己写个测试实例以作记录
poi-tl版本
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.1</version>
</dependency>
-
具体代码:
@Data public class WordVO private List<PictureRenderData> picture; private String problem; private String reason;
package com.twy.controller; import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.config.Configure; import com.deepoove.poi.data.PictureRenderData; import com.deepoove.poi.data.TextRenderData; import com.deepoove.poi.policy.ListRenderPolicy; import com.twy.entity.WordVO; import org.apache.commons.collections4.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @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.builder().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<>(); String location = System.getProperty("user.dir") + "/poi-tl/src/main/resources/"; pList1.add(new PictureRenderData(100, 120, location + "img/1.jpg")); pList1.add(new PictureRenderData(100, 120, location + "img/2.jpg")); pList2.add(new PictureRenderData(100, 120, location + "img/3.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(location + "result/test.docx");
代码结构目录:
- word模板
- 导出结果
以上是关于poi-tl动态遍历的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot集成文件 - 如何基于POI-tl和word模板导出庞大的Word文件?