I have a solution for this. Essentially, I just translated your thoughts into Java code.
First you will need these 2 methods.
The first helps determine if a given cell is in a merged cell.
private Integer getIndexIfCellIsInMergedCells(Sheet sheet, int row, int column) { int numberOfMergedRegions = sheet.getNumMergedRegions(); for (int i = 0; i < numberOfMergedRegions; i++) { CellRangeAddress mergedCell = sheet.getMergedRegion(i); if (mergedCell.isInRange(row, column)) { return i; } } return null; }
And the second helps you extract content from it.
private String readContentFromMergedCells(Sheet sheet, CellRangeAddress mergedCells) { if (mergedCells.getFirstRow() != mergedCells.getLastRow()) { return null; } return sheet.getRow(mergedCells.getFirstRow()).getCell(mergedCells.getFirstColumn()).getStringCellValue(); }
Then you can iterate over the rows and columns on this sheet and perform different actions depending on whether this cell is in the merged cell or not.
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); if (row == null) { continue; } int lastColumn = row.getLastCellNum(); for (int columnNum = 0; columnNum < lastColumn; columnNum++) { // Determine if this cell is in a merged cell Integer mergedCellIndex = getIndexIfCellIsInMergedCells(sheet, rowNum, columnNum); if (mergedCellIndex != null) { // If it is in a merged cell // then get it CellRangeAddress cell = sheet.getMergedRegion(mergedCellIndex); // Do your logic here log.info("Cell is in a merged cell"); log.info("Content is {}", readContentFromMergedCells(sheet, sheet.getMergedRegion(mergedCellIndex))); // Get the last column of this merged cell int lastColumnOfThisMergedCell = sheet.getMergedRegion(mergedCellIndex).getLastColumn(); // And skip those merged cells // since the columnNum will increase 1 on next loop // so you have to minus 1 here columnNum = columnNum + lastColumnOfThisMergedCell - 1; log.info("Next column being processed is {}", columnNum); } else { // If it is not in a merged cell // hence, an "individual" cell Cell cell = row.getCell(columnNum, Row.RETURN_BLANK_AS_NULL); if (cell == null) { continue; } // Then you can simply do your logic // and continue to the next loop log.info("Cell is an individual cell"); log.info("Content is {}", row.getCell(columnNum).getStringCellValue()); } } }
boris1993
source share