Cell merging in Excel combines two or more adjacent cells in the same row or column into a single cell. This article demonstrates how to use Free Spire.XLS for Java to merge and unmerge cells in Excel spreadsheets.
Prerequisites:
- Download Free Spire.XLS for Java and extract the package. Add the Spire.Xls.jar file from the lib folder as a dependency in your Java project.
- Alternatively, configure Maven to include the library by adding the following to your pom.xml:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
Merging Cells:
The following example demonstrates how to merge a range of cells (A1 to C1) in an Excel worksheet:
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class CellMerger {
public static void main(String[] args) {
// Initialize a new Workbook
Workbook wb = new Workbook();
// Load an existing Excel file
wb.loadFromFile("input.xlsx");
// Access the first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Merge the cell range from A1 to C1
ws.getRange().get("A1:C1").merge();
// Save the modified workbook
wb.saveToFile("merged_output.xlsx", FileFormat.Version2013);
}
}
Unmerging Cells:
To unmerge previously merged cels, use the unMerge() method as shown below:
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class CellUnmerger {
public static void main(String[] args) {
// Initialize a new Workbook
Workbook wb = new Workbook();
// Load the Excel file containing merged cells
wb.loadFromFile("merged_output.xlsx");
// Access the first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Unmerge the cell range from A1 to C1
ws.getRange().get("A1:C1").unMerge();
// Save the result to a new file
wb.saveToFile("unmerged_output.xlsx", FileFormat.Version2013);
}
}
The merge() method accepts cell ranges in standard Excel notation (such as "A1:C1", "B2:E5", or "A1"), while the unMerge() method works on the same range format to restore individual cells.