Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 287
Đinh Hồng Châu Avatar asked Jun 08 '11 07:06

Đinh Hồng Châu


1 Answers

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 http://www.google.com/codesearch/p?hl=de#WXzbfAF-tQc/trunk/src/java/org/apache/poi/hssf/usermodel/HSSFSheet.java

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) {
                notNullCount++;
                break;
            }
        }
    }
}
like image 174
Wolfgang Kuehn Avatar answered Sep 18 '22 20:09

Wolfgang Kuehn