通过这个简单的例子,再去和自己的业务结合
官网http://deepoove.com/poi-tl/
官网有其它完整的例子:http://deepoove.com/poi-tl/#hack-loop-table
1.导包
( 注意: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>
2.需要动态添加的模板

3.使用
3.1 需要循环添加内容的实体类
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;
}
}
3.2 获取数据和模板进行填充
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();
}
}
输出结果:

本文介绍了如何通过poi-tl库在Java中创建动态模板,并结合TestLoopRowTable实体类,实现数据源循环填充Word表格。通过实例展示了从模板读取、配置循环策略到渲染数据的具体步骤。
3212





