Detect Merged Cells in a Worksheet

Demonstration

This example uses a template Microsoft Excel file called MergeTrial. It has some merged cell areas in a sheet also called Merge Trial.

The template file

todo:image_alt_text

Aspose.Cells provides the Cells.getMergedCells() method which is used to get all merged cells.

When the code below is executed, it clears the contents of the sheet and unmerges all the cell areas before saving the file again.

The Output File

todo:image_alt_text

Code Example

Please see the following sample code to find how to identify merged cell areas in a worksheet and unmerge them.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectMergedCells.class);
// Instantiate a new Workbook
Workbook wkBook = new Workbook(dataDir + "MergeTrial.xls");
// Get a worksheet in the workbook
Worksheet wkSheet = wkBook.getWorksheets().get("Merge Trial");
// Clear its contents
wkSheet.getCells().clearContents(0, 0, wkSheet.getCells().getMaxDataRow(),
wkSheet.getCells().getMaxDataColumn());
// Get all merged cell aeras
CellArea[] areas = wkSheet.getCells().getMergedAreas();
// Define some variables
int frow, fcol, erow, ecol;
// Loop through the arraylist and get each cellarea to unmerge it
for (int i = areas.length - 1; i > -1; i--)
{
frow = areas[i].StartRow;
fcol = areas[i].StartColumn;
erow = areas[i].EndRow;
ecol = areas[i].EndColumn;
wkSheet.getCells().unMerge(frow, fcol, erow, ecol);
}
// Save the excel file
wkBook.save(dataDir + "output_MergeTrial.xls");
  • Merging and splitting cells.