Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
mergeCells(table.getRows().get(0).getCells().get(0),table.getRows().get(1).getCells().get(0));
/**
* 合并单元格
* @param startCell 起始单元格
* @param endCell 结束单元格
*/
public static void mergeCells(Cell startCell, Cell endCell) {
Table parentTable = startCell.getParentRow().getParentTable();
// Find the row and cell indices for the start and end cell.
Point startCellPos = new Point(startCell.getParentRow().indexOf(startCell), parentTable.indexOf(startCell.getParentRow()));
Point endCellPos = new Point(endCell.getParentRow().indexOf(endCell), parentTable.indexOf(endCell.getParentRow()));
// Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.
Rectangle mergeRange = new Rectangle(Math.min(startCellPos.x, endCellPos.x), Math.min(startCellPos.y, endCellPos.y), Math.abs(endCellPos.x - startCellPos.x) + 1,
Math.abs(endCellPos.y - startCellPos.y) + 1);
for (Row row : parentTable.getRows()) {
for (Cell cell : row.getCells()) {
Point currentPos = new Point(row.indexOf(cell), parentTable.indexOf(row));
// Check if the current cell is inside our merge range then merge it.
if (mergeRange.contains(currentPos)) {
if (currentPos.x == mergeRange.x)
cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
else
cell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
if (currentPos.y == mergeRange.y)
cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
else
cell.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
}
}
}
}