DEV Community

CodeSharing
CodeSharing

Posted on

Merge and Unmerge Cells in Excel in Java

Merging cells is the operation of merging two or more cells in the same row or column into one cell. It is often used when we need to apply a header across multiple columns or rows. This article will introduce how to merge and unmerge cells in an Excel file by using Free Spire.XLS for Java.

Installation
Method 1: Download the Free Spire.XLS for Java and unzip it. Then add the Spire.Xls.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>2.2.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Merge cells:

import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class MergeCells {
    public static void main(String[] args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("test1.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        //Merge cells by range
        sheet.getRange().get("A1:C1").merge();

        //Save the resultant file
        workbook.saveToFile("MergeCells.xlsx", FileFormat.Version2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Unmerge cells:

import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class UnmergeCells {
    public static void main(String[] args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("MergeCells.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        //Unmerge cells by range
        sheet.getRange().get("A1:C1").unMerge();

        //Save the resultant file
        workbook.saveToFile("UnMergeCells.xlsx", FileFormat.Version2013);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)