前言
Java使用poi-tl 实现word表格模板动态渲染表格
由于公司内网只有1.6.0版本,本次使用的是1.6.0版本进行的开发
场景分析
用户在前端页面进行构建理财产品组合时会选择1~N种产品,所以需要word模板对应区域动态生成多行产品行,并将其中内容替换,模板类似下图。
依赖引入
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.6.0</version>
</dependency>
代码参考
代码如下(示例):其中word模板需要在任意表格内加入一个标识,本文使用的是’${detail_table}’
public static void main(String[] args) throws IOException {
Map<Object, Object> datas = new HashMap<>();
datas.put("E1", "张三");
datas.put("E2", "6R");
datas.put("E3", "均衡型");
datas.put("E4", "李丹");
datas.put("A1", "15%");
datas.put("A2", "6%");
datas.put("A3", "3%");
datas.put("C1", "15%");
datas.put("C2", "16%");
datas.put("C3", "12%");
datas.put("C4", "11%");
datas.put("C5", "18%");
datas.put("D1", "14%");
datas.put("D2", "10%");
datas.put("D3", "16%");
datas.put("D4", "17%");
datas.put("D5", "11%");
TableStyle rowStyle = new TableStyle();
rowStyle = new TableStyle();
rowStyle.setAlign(STJc.CENTER);
Map<Object, Object> detailTable = new HashMap<>();
Style style = new Style();
style.setFontFamily("微软雅黑");
style.setFontSize(12);
TextRenderData text1 = new TextRenderData("测试11", style);
TextRenderData text2 = new TextRenderData("测试22", style);
RowRenderData labor = RowRenderData.build(text1,text2,text1,text2);
RowRenderData labor1 = RowRenderData.build(text2,text1,text2,text1);
labor.setRowStyle(rowStyle);
labor1.setRowStyle(rowStyle);
List<RowRenderData> labors = Arrays.asList(labor, labor1);
detailTable.put("labors", labors);
datas.put("detail_table", detailTable);
Configure config = Configure.newBuilder().buildGramer("${", "}").bind("detail_table", new DetailTablePolicy()).build();
XWPFTemplate template = XWPFTemplate.compile("D:\\word\\template.docx", config).render(datas);
template.writeToFile("D:\\word\\write.docx");
}
public class DetailTablePolicy extends DynamicTableRenderPolicy {
// 人工费填充数据所在行数
int laborsStartRow = 6;
@Override
public void render(XWPFTable table, Object data) {
if (null == data) return;
Map<Object, Object> detailData = (Map<Object, Object>) data;
List<RowRenderData> labors = (List<RowRenderData>) detailData.get("labors");
XWPFTableRow copyRow = table.getRow(5);
List<XWPFTableCell> cellList = copyRow.getTableCells();
if (null != labors) {
table.removeRow(laborsStartRow);
// 循环插入行
for (int i = 0; i < labors.size(); i++) {
XWPFTableRow insertNewTableRow = table.insertNewTableRow(laborsStartRow);
for (int j = 0; j < 4; j++) {
XWPFTableCell sourceCell = cellList.get(j);
//插入一个单元格
XWPFTableCell targetCell = insertNewTableRow.createCell();
//复制列属性
targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
}
// 渲染单行人工费数据
MiniTableRenderPolicy.Helper.renderRow(table, laborsStartRow, labors.get(i));
laborsStartRow++;
}
}
}
}
生成的效果图如下
总结
参考文档:参考文档:http://deepoove.com/poi-tl/1.6.x/
如想使用高版本,看着官网稍微一改动即可正常运行