Why "cellIterator.hasNext()" is getting "TRUE" even though cell has empty value

4.5k views Asked by At

consider below screenshot of my excelSheet

enter image description here

Now consider below code, which will iterate every row then iterate every cell and then print cell value.

public void excelData2(int sheetNo) {
    Iterator<Row> rowIterator = workbook.getSheetAt(sheetNo).rowIterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            String cellValue = dataFormatter.formatCellValue(cell);
            System.out.print(cellValue + "\t");
        }
        System.out.println();
    }
}

Actually by looking at excel sheet we can see there are 2 rows and 1 column right!!.

So, the first while loop is iterating two times as expected :) , but inner while loop which is cellIterator is looping 26 times instead of 1 time even though next cell's has no value in it. Ideally when in 2nd iteration cellIterator.hasNext() should give false right? why it is giving true value till 26 times? anyone have idea?

Note: I don't want to put condition like isEmpty() or =="" etc.

Note2: I have another solution in my mind i can go with that. But i want to know why this is happening.

2

There are 2 answers

0
RajmondX On

According to the docs of POI (used by LibreOffice):

org.apache.poi.xssf.streaming.SXSSFRow.CellIterator

returns all cells including empty cells

0
pshetty On

You can use this and can skip the blank once:

if (nextCell.getCellType() == Cell.CELL_TYPE_BLANK)