Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Last active August 30, 2024 17:08
Merge Cells in Word using Java. For further details: https://kb.aspose.com/words/java/merge-cells-in-word-using-java/
import com.aspose.words.*;
import java.awt.*;
public class Main
{
static void mergeCells(Cell startCell, Cell endCell)
{
Table parentTable = startCell.getParentRow().getParentTable();
// Define start and ending 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 a range of cells
Rectangle range = new Rectangle(Math.min(startCellPos.x, endCellPos.y), Math.min(startCellPos.y, endCellPos.y),
Math.abs(endCellPos.x - startCellPos.x) + 1, Math.abs(endCellPos.y - startCellPos.y) + 1);
for (Row currentRow : parentTable.getRows())
{
for (Cell cell : currentRow.getCells())
{
Point currentPos = new Point(currentRow.indexOf(cell), parentTable.indexOf(currentRow));
// Validate the current cell
if (range.contains(currentPos))
{
cell.getCellFormat().setHorizontalMerge(currentPos.x == range.getX() ? CellMerge.FIRST : CellMerge.PREVIOUS);
cell.getCellFormat().setVerticalMerge(currentPos.y == range.getY() ? CellMerge.FIRST : CellMerge.PREVIOUS);
}
}
}
}
public static void main(String[] args) throws Exception // Merge Table Cells in Java
{
// Set the licenses
new License().setLicense("License.lic");
Document tableDoc = new Document("Table.docx");
Table tbl = tableDoc.getFirstSection().getBody().getTables().get(1);
Cell startingCell = tbl.getRows().get(1).getCells().get(1);
Cell endingCell = tbl.getRows().get(2).getCells().get(2);
// Merge the cells
mergeCells(startingCell, endingCell);
tableDoc.save("MergeCells.docx");
System.out.println("Word table merged successfully");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment