In the past I use following code to display first cell string of all rows.
1 2 3 4 5 6 |
for(int i=0; i<sheet.getPhysicalNumberOfRows(); i++){ Row row = sheet.getRow(i); if(row == null || row.getCell(0) == null){ System.out.println(row.getCell(0).getStringCellValue()); } } |
But above code will be incorrect if there is empty row.
Following is explanation from POI official documentation
Sheet.getPhysicalNumberOfRows()
Returns the number of physically defined rows (NOT the number of rows in the sheet)
This method will ignore empty rows, e.g. if a sheet last row is at row 7, but second row is empty, getPhysicalNumberOfRows() will return 6.
Solution
To get row count of a sheet (no matter the row is empty or not), we should use getLastRowNum() method.
So above code can be changed to
1 2 3 4 5 6 |
for(int i=0; i<=sheet.getLastRowNum(); i++){ Row row = sheet.getRow(i); if(row == null || row.getCell(0) == null){ System.out.println(row.getCell(0).getStringCellValue()); } } |
Because getLastRowNum() method returns 0-based row index, so we use i<=sheet.getLastRowNum() as the loop condition.