Home > Net >  cellIterator.hasNext() returns false even the cell has value
cellIterator.hasNext() returns false even the cell has value

Time:10-12

I use the following approach to read data from excel (csv) sheet:

InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
XSSFWorkbook myWorkBook = new XSSFWorkbook(inputStream);
List<String> cellList = new ArrayList<>();
XSSFSheet mySheet = myWorkBook.getSheetAt(0);

Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();

while (rowIterator.hasNext()) {
    Row row = rowIterator.next();
    cellList.clear();
    Iterator<Cell> cellIterator = row.cellIterator();

    while (cellIterator.hasNext()) { // this returns false even the cell has data 
        Cell cell = cellIterator.next();
        cellList.add(cell.getStringCellValue());
    }
}

I want to make cellIterator.hasNext() returns true for empty cell values as in the second row (name). So, how can I do that?

Create Date  Uuid                                  Name
2021-09-29   2e81a2b6-3226-4fe0-b8bd-39f42239686d  admin
2021-09-30   610e9040-840c-48c5-aa64-f193ed896133  

CodePudding user response:

You can't make cellIterator.hasNext() return true for the empty "name" cell.

If you know in advance the number of column in advance, you can use a loop and row.getCell(index).

        for (int i = 0; i < 3; i  ) {
            Cell cell = row.getCell(i);
            cellList.add(cell == null ? "Empty":cell.toString());
        }

If you don't, you have to scan first of your file to count the number of columns.

  • Related