When there are merged cells in your worksheet, you may experience problems performing certain operations, such as sorting data. For such cases, Microsoft Excel provides a built-in feature – “Find and Replace” – that allows you to find merged cells within a worksheet. Once the merged cells are found, you can process them further, for example, highlighting them or unmerging them. In this article, I will demonstrate how to achieve this task programmatically in Java using Free Spire.XLS for Java API.
Add Dependencies
To begin with, you need to add needed dependencies for including Free Spire.XLS for Java library into your Java project. You can either download the library’s jar from the official website or install it from Maven by adding the following code to your maven-based project’s pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>
Identify Merged Cells in Excel
The following are the steps to identify merged cells in an Excel worksheet:
- Create an instance of Workbook class and load the Excel file using Workbook.loadFromFile() method.
- Get the desired worksheet using Workbook.getWorksheets().get() method.
- Get the merged range of cells into a CellRange array using Worksheet.getMergedCells() method.
- Loop through the array, highlight the merged cells using CellRange.getCellStyle().setColor() method.
- Save the result file using Workbook.saveToFile() method.
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import java.awt.*;
public class IdentifyMergedCells {
public static void main(String []args){
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile( "Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Get the merged cell ranges in the worksheet into a CellRange array
CellRange[] range = sheet.getMergedCells();
//Traverse through the array
for(CellRange cell : range){
//Highlight the merged cells
cell.getCellStyle().setColor(Color.YELLOW);
//Unmerge the merged cells
//cell.unMerge();
}
//Save the result file
workbook.saveToFile("IdentifyMergedCells.xlsx", ExcelVersion.Version2013);
}
}
The result file after highlighting merged cells:
![](https://officedevblogs805426550.wordpress.com/wp-content/uploads/2021/11/identifymergedcells.png?w=647)
See Also: Merge and Unmerge Excel Cells in Java