如何合并具有相同内容的单元格

如何在第二列,向下合并具有相同内容的单元格,实现以下表格效果


可能还会有更多数据

@JOOL 该表格有一个垂直合并单元格。 您可以使用以下代码来实现:

Document doc = new Document("input.docx");

Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
mergeCellsWithSameValuesInColumns(table);

doc.save("output.docx");

private static void mergeCellsWithSameValuesInColumns(Table table) {
    // 迭代每一列(假设所有行的单元格数量相同)。
    for (int colIdx = 0; colIdx < table.getFirstRow().getCells().getCount(); colIdx++) {
        // 从第一行开始,与下一行进行比较。
        for (int rowIdx = 0; rowIdx < table.getRows().getCount() - 1; rowIdx++) {
            Cell currentCell = table.getRows().get(rowIdx).getCells().get(colIdx);
            Cell nextCell = table.getRows().get(rowIdx + 1).getCells().get(colIdx);

            // 比较当前单元格和下一单元格的文本。
            if (currentCell.getText().trim().equals(nextCell.getText().trim())) {
                // If the current cell is not part of a previous merge, start a new merge
                if (currentCell.getCellFormat().getVerticalMerge() == CellMerge.NONE) {
                    currentCell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
                }
                // 将下一个单元格合并到当前合并范围。
                nextCell.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
            }
        }
    }
}