模板
package com.example.service.Impl;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.policy.DynamicTableRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import com.example.entity.DetailData;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import java.util.List;
public class DetailTablePolicy extends DynamicTableRenderPolicy {
// 货品填充数据所在行数
int goodsStartRow = 2;
// 人工费填充数据所在行数
int laborsStartRow = 5;
@Override
public void render(XWPFTable table, Object data) throws Exception {
if (null == data) return;
DetailData detailData = (DetailData) data;
System.out.println(data);
// 人工费循环渲染
List<RowRenderData> labors = detailData.getLabors();
if (null != labors) {
table.removeRow(laborsStartRow);
// 循环插入行
for (int i = 0; i < labors.size(); i++) {
XWPFTableRow insertNewTableRow = table.insertNewTableRow(laborsStartRow);
for (int j = 0; j < 7; j++) insertNewTableRow.createCell();
// 合并单元格
TableTools.mergeCellsHorizonal(table, laborsStartRow, 0, 3);
// 渲染单行人工数据
TableRenderPolicy.Helper.renderRow(table.getRow(laborsStartRow), labors.get(i));
}
}
// 货品循环渲染
List<RowRenderData> goods = detailData.getGoods();
if (null != goods) {
table.removeRow(goodsStartRow);
// 循环插入行
for (int i = 0; i < goods.size(); i++) {
XWPFTableRow insertNewTableRow = table.insertNewTableRow(goodsStartRow);
for (int j = 0; j < 7; j++) {
insertNewTableRow.createCell();
}
TableRenderPolicy.Helper.renderRow(table.getRow(goodsStartRow), goods.get(i));
}
}
}
}
@Test
public void testDynamicGenerateTable() throws Exception{
DetailData detailTable = new DetailData();
// 初始化数据
RowRenderData good = Rows.of("4", "墙纸", "书房+卧室", "1500", "/", "400", "1600").center().create();
List<RowRenderData> goods = Arrays.asList(good, good, good, good);
RowRenderData labor = Rows.of("油漆工", "2", "200", "400").center().create();
List<RowRenderData> labors = Arrays.asList(labor, labor, labor, labor);
detailTable.setGoods(goods);
detailTable.setLabors(labors);
Configure config = Configure.builder().bind("detail_table", new DetailTablePolicy()).build();
XWPFTemplate template = XWPFTemplate.compile("D:\\Idea-projects\\POI_word\\templates_payment.docx",config);
Map<String, Object> map = new HashMap<>();
map.put("detail_table", detailTable);
template.render(map);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Idea-projects\\POI_word\\output_payment.docx");
template.writeAndClose(fileOutputStream);
template.close();
}
结果
?
?