简体   繁体   中英

Checking for empty row in excel using apache poi methods

Can I check for empty rows in excel using apache POI methods

XSSFSheet sheet = workbook.getSheetAt(i); 
sheet.getRow(0)!= null;

I am thinking of trying this, but I just wanted to check if there would be any problems later on with this. Any suggestion?
Thanks

The Excel file formats only store rows that were actually created, ie "sparse storage". That means for rows-indices that were not used at all you will get back null .

But there might be cases where a row was created but no cells added or all cells removed again, so to be absolutely sure you likely will also need to check the existing rows and make sure that there are cells in it.

For cells it is similar, they are only non-null for a certain cell-index if they have been created before.

You can use the below method to check for empty row.

private boolean checkIfRowIsEmpty(HSSFRow row) {
        if (row == null || row.getLastCellNum() <= 0) {
            return true;
        }
        HSSFCell cell = row.getCell((int)row.getFirstCellNum());
        if (cell == null || "".equals(cell.getRichStringCellValue().getString())) {
            return true;
        }
        return false;
    }

We can use this if XSSFWorkbook used

private boolean checkIfRowIsEmpty(XSSFRow row) {
    if (row == null || row.getLastCellNum() <= 0) {
        return true;
    }
    XSSFCell cell = row.getCell((int)row.getFirstCellNum());
    if (cell == null || "".equals(cell.getRichStringCellValue().getString())) {
        return true;
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM