Java – Count not null row in Excel file using Apache POI


Does Apache POI provide any function for us to count the number of "not-null" rows in a sheet of an Excel file?
At the first time, I have an Excel sheet with 10 data rows, the function worksheet.getPhysicalNumberOfRows() returns the exact number (10). But after that, I delete 3 rows, then that function still gets 10 rows. Maybe the total number of rows was cached anywhere by POI. What does getPhysicalNumberOfRows() mean? As its API described: "Returns the number of physically defined rows (NOT the number of rows in the sheet)", but I do not understand what "physically defined" mean. Can you help me on this issue?
Thank you so much!

Best Solution

If you delete the rows via worksheet.removeRow(Row row), then the physical row count should be 7.

POI uses a map to store the rows of a sheet. This map is the physical part. See

As to the logically null rows, try

int notNullCount = 0;
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
    for (Cell cell : row) {
        if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
            if (cell.getCellType() != Cell.CELL_TYPE_STRING ||
                cell.getStringCellValue().length > 0) {
Related Question