赞
踩
官网有其它完整的例子:http://deepoove.com/poi-tl/#hack-loop-table
( 注意:poi-tl低版本没有LoopRowTableRenderPolicy ,下面是目前最新版)
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.0</version>
</dependency>
<!-- JSON类需要这个依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
package org.app.test; public class TestLoopRowTable { private String xh; private String nr; public TestLoopRowTable(String xh, String nr) { this.xh = xh; this.nr = nr; } public TestLoopRowTable() { } @Override public String toString() { return "TestLoopRowTable{" + "xh='" + xh + '\'' + ", nr='" + nr + '\'' + '}'; } public String getXh() { return xh; } public void setXh(String xh) { this.xh = xh; } public String getNr() { return nr; } public void setNr(String nr) { this.nr = nr; } }
import com.alibaba.fastjson.JSON; import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.config.Configure; import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; public class TestTable { @org.junit.jupiter.api.Test public void testTable() throws IOException { // compile 编译模板 // render 渲染数据 // write 输出到流 // TDO模式:Template + data-model = output // 模板文件地址 String filePath= "D:\\codes\\08\\miaosha\\src\\main\\resources\\static\\tableTest.docx"; // 读取模板后保存生成word的地址 String outPath = "D:\\codes\\08\\miaosha\\src\\main\\resources\\static\\tableTestOut.docx"; // 为表格的显示绑定行循环 LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy(); // 将bz设置为行循环绑定的数据源的key,即key是bz的value会在模板中的{{bz}}处进行解析 Configure configure = Configure.builder().bind("bz", policy).build(); // 将需要解析的数据放到map中 HashMap<String, Object> map = new HashMap<String, Object>() { { // 其他业务获取到数据源 String testTable = "[{\"xh\":\"1\",\"nr\":\"内容1\"},{\"xh\":\"2\",\"nr\":\"内容2\"},{\"xh\":\"3\",\"nr\":\"内容3\"}]"; // 内容在表格里循环 // JSON使用,需要导入fastjson依赖 List<TestLoopRowTable> forms = JSON.parseArray(testTable, TestLoopRowTable.class); for (int i = 0; i < forms.size(); i++) { put("xh" + i, forms.get(i).getXh()); put("nr" + i, forms.get(i).getNr()); } put("bz", forms); } }; // 读取模板、数据并渲染 XWPFTemplate template = XWPFTemplate.compile(filePath, configure).render(map); // 文件是否已存在,则删除 File file = new File(outPath); if (file.exists()){ file.delete(); } // 生成word保存在指定目录 template.writeToFile(outPath); template.close(); } }
输出结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。