关于表格插入一行,并合并单元格

源文档:
给对方.docx (21.7 KB)

代码:

Document document = new Document("D:\\xxx\\给对方.docx");
document.startTrackRevisions("EDITOR", new Date());
NodeCollection childNodes = document.getChildNodes(NodeType.TABLE, true);
Arrays.stream(childNodes.toArray()).forEach(table -> {
    Row newRow = insertRow(document, (Table) table);
    CellCollection cells = newRow.getCells();
    for (Cell cell : cells) {
        int index = cells.indexOf(cell);
        if (index == 0) {
            cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
            continue;
        }
        cell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
    }
});
document.save("D:\\xxx\\fd.docx");

public static Row insertRow(Document document, Table table) {
    table.convertToHorizontallyMergedCells();
    Row lastRow = table.getLastRow();
    Row row = new Row(document);
    CellCollection cells = lastRow.getCells();
    for (Cell cell : cells) {
        Cell newCell = new Cell(document);
        row.appendChild(newCell);
    }
    table.appendChild(row);
    return row;
}

得到的文档:
fd.docx (20.2 KB)


期望得到的结果是,第一个表格最后一行也是合并起来的,为什么只有第二个表格的结果正确了呢

@ouchli To get the expected output it would be better to clone last row instead of creating new row. Please modify your code like this:

public static Row insertRow(Document document, Table table)
{
    Row lastRow = table.getLastRow();
    Row row = (Row)lastRow.deepClone(true);
    // Remove content from the cloned row.
    row.getChildNodes(NodeType.RUN, true).clear();
    table.appendChild(row);
    return row;
}