logo

Apache POI Merging Excel Cells

Java Code Examples for:

  • org.apache.poi.ss.util.CellRangeAddress class
  • org.apache.poi.ss.usermodel.Sheet.addMergedRegion() method

In Java example code below we show you how to create Excel file with merged cell.

Apache POI Library Dependencies

Define below dependencies in build.gradle if you are using Gradle build.

compile group: 'org.apache.poi', name: 'poi', version: '4.0.1'

Define this dependencies in pom.xml if you are using Maven build.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>

How to merge Excel cells using Apache POI library

To merge cells to need to create object of CellRangeAddress class and provide cell range of merging then add to Sheet using addMergedRegion method. For example below we merge a cell with 4 column in width and 5 column in height:

sheet.addMergedRegion(new CellRangeAddress(
    0, //first row index in zero-based
    4, //last row index in zero-based
    0, //first column index in zero-based
    3  //last column index in zero-based
));

Example application to merge Excel cells

package simplesolution.dev;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ApachePOIMergeCellsExample {

    public static void main(String... args) {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("merge-cells-example");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("SimpleSolution.dev");

        sheet.addMergedRegion(new CellRangeAddress(
                0, //first row index in zero-based
                4, //last row index in zero-based
                0, //first column index in zero-based
                3  //last column index in zero-based
        ));

        try (OutputStream fileOut = new FileOutputStream("merge-cells.xls")) {
            workbook.write(fileOut);
            workbook.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
The ouput file:

Apache POI Merging Excel Cells Output File

The source code in this article can be found at: github.com/simplesolutiondev/ApachePOIMergingCells

or download at:

Download Source Code

Happy Coding 😊

Apache POI Excel Cell Fonts

Apache POI Excel Cell Border and Border Color

Apache POI Vertical and Horizontal Excel Cell Alignment

Apache POI Excel Cell Background Foreground and Font Color

Tags: