@wang0707 没有内置的方法来拆分表格中的单元格。 要水平分割单元格,需要克隆单元格并将其添加到要分割的单元格后面,然后相应地调整单元格宽度。 如果垂直分割单元格,事情会有点困难。 需要克隆该行并垂直合并克隆行中的单元格。 这就是垂直分割单元格时 MS Word 所做的操作。 下面是实现垂直和水平单元格分割操作的代码示例:
Document doc = new Document("C:\\Temp\\in.docx");
// Get the table.
Table table = doc.getFirstSection().getBody().getTables().get(0);
// Split the first cell of the first row vertically.
splitCellVertically(table.getFirstRow().getFirstCell(), 5);
// Split the last cell of the last row horizontally.
splitCellHorizontally(table.getLastRow().getLastCell(), 5);
doc.save("C:\\Temp\\out.docx");
private static void splitCellVertically(Cell c, int cells)
{
// Get parent row of the cell.
Row parentRow = c.getParentRow();
// Get the cell index
int cellIndex = parentRow.getCells().indexOf(c);
// Set vertical cell merge in the parent row.
// This row is the first.
for (Cell cell : parentRow.getCells())
{
if (cell != c)
cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
}
// Clone and add the row below the parent row.
for (int i = 0; i < cells-1; i++)
{
Row r = (Row)parentRow.deepClone(true);
// Merge cells with previous.
for (Cell cell : r.getCells())
{
// Remove content from the cell
cell.removeAllChildren();
cell.ensureMinimum();
if (r.getCells().indexOf(cell) != cellIndex)
cell.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
}
// Insert the cell below the parent cell
parentRow.getParentNode().insertAfter(r, parentRow);
}
}
private static void splitCellHorizontally(Cell c, int cells)
{
double newCellWidth = c.getCellFormat().getWidth() / cells;
c.getCellFormat().setWidth(newCellWidth);
for (int i = 0; i < cells - 1; i++)
c.getParentRow().insertAfter(c.deepClone(false), c);
}
1 Like
