How to read from merged cells of Excel in Java using Apache POI? How to read from merged cells of Excel in Java using Apache POI? apache apache

How to read from merged cells of Excel in Java using Apache POI?


Following code of snippet might help.

while (rowIterator.hasNext()) {        Row row = rowIterator.next();        //For each row, iterate through all the columns        Iterator<Cell> cellIterator = row.cellIterator();        outer:        while (cellIterator.hasNext()) {            Cell cell = cellIterator.next();            //will iterate over the Merged cells            for (int i = 0; i < sheet.getNumMergedRegions(); i++) {                CellRangeAddress region = sheet.getMergedRegion(i); //Region of merged cells                int colIndex = region.getFirstColumn(); //number of columns merged                int rowNum = region.getFirstRow();      //number of rows merged                //check first cell of the region                if (rowNum == cell.getRowIndex() && colIndex == cell.getColumnIndex()) {                    System.out.println(sheet.getRow(rowNum).getCell(colIndex).getStringCellValue());                    continue outer;                }            }            //the data in merge cells is always present on the first cell. All other cells(in merged region) are considered blank            if (cell.getCellType() == Cell.CELL_TYPE_BLANK || cell == null) {                continue;            }            System.out.println(cell.getStringCellValue());        }    }


This method can read a specific cell (including merged cell):

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import org.apache.poi.ss.usermodel.DateUtil;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFWorkbook;public static void readCell(String excelFilePath, int rowIndex, int columnIndex) throws FileNotFoundException, IOException {    try (InputStream inp = new FileInputStream(excelFilePath)) {        XSSFWorkbook wb = new XSSFWorkbook(inp);        XSSFCell cell = wb.getSheetAt(0).getRow(rowIndex).getCell(columnIndex);        switch (cell.getCellType()) {        case STRING:            System.out.println(cell.getRichStringCellValue().getString());            break;        case NUMERIC:            if (DateUtil.isCellDateFormatted(cell)) {                System.out.println(cell.getDateCellValue());            } else {                System.out.println(cell.getNumericCellValue());            }            break;        case BOOLEAN:            System.out.println(cell.getBooleanCellValue());            break;        case FORMULA:            System.out.println(cell.getCellFormula());            break;        case BLANK:            System.out.println();            break;        default:            System.out.println();        }        wb.close();    }}

Dependencies: POI 5.0.0, JDK 1.8.0