问题:您好,麻烦可以帮忙看一下为什么合并单元格不生效吗。
步骤:我是先填充表格数据,然后想要把表格里面的某一行进行单元格合并,但是我发现合并的操作好像不能够生效。
这个是模板文件:test.docx (10.4 KB)
@Data
@AllArgsConstructor
public class Test {
private String a;
private String h;
}
@Slf4j
public class LicenseUtil {
public static void main(String[] args) throws Exception {
Document document = new Document("test.docx");
List<Test> list = new ArrayList<>();
Test test = new Test("first cell, this is 'a' cell", "last cell, this is 'h' cell");
list.add(test);
list.add(test);
list.add(test);
fillCommodityList("Test", BeanUtil.listObjectToMap(list), document.getMailMerge());
mergeRow(document);
document.save("C:\\fps\\test.pdf");
}
public static void fillCommodityList(String tableName, List<LinkedHashMap<String, String>> dataSet, MailMerge merge) throws Exception {
// 将 dataSet 转成 DataTable
if (dataSet != null && !dataSet.isEmpty()) {
// 与模板里面的TableStart:xx(名称对应)
DataTable dataTable = new DataTable(tableName);
for (int i = 0; i < dataSet.size(); i++) {
// 加上填充数据的字段
if (i == 0) {
for (String key : dataSet.get(0).keySet()) {
dataTable.getColumns().add(key);
}
}
// 写入数据
DataRow dataRow = dataTable.newRow();
LinkedHashMap<String, String> line = dataSet.get(i);
for (DataColumn dc : dataTable.getColumns()) {
if (line.containsKey(dc.getColumnName())) {
String columnName = dc.getColumnName();
String value = line.get(dc.getColumnName());
if (value == null) {continue;}
dataRow.set(columnName, value);
}
}
dataTable.getRows().add(dataRow);
}
merge.executeWithRegions(dataTable);
}
}
public static void mergeRow(Document doc) {
try {
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
for (Row row : table.getRows()) {
Cell firstCell = row.getCells().get(0);
firstCell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
}