简体   繁体   中英

Reading from excel files using JAVA poi and ignoring empty cells

I was trying to read data from an excel sheet that contains empty cells consider the following code:

File src = new File(path to your file); 
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
        
XSSFSheet sheet1 = wb.getSheet("Sheet1");
int rowCount = sheet1.getLastRowNum();
System.out.println("total number of rows is: " + rowCount);
for(int i = 1; i < rowCount; i++) {
    //getcell returns row num and starts from 1
    //Also my sheet column contains data in numeric form
    int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();

    System.out.println(data);
}

However, my code also reads the empty cells and displays the value as 0 (The cells have numeric value). How do I make my script read-only cells that are filled and display them while ignoring the ones that are empty?

Thank you in advance

Just update the for loop with an if condition which will check for the value which is getting retrieved from the Cell. PFB the updated for loop.

For Apache POI version 4.x you can try below-

    for(int i = 1; i < rowCount; i++) {
       //getcell returns row num and starts from 1
       //Also my sheet column contains data in numeric form
       Cell cell  = sheet1.getRow(i).getCell(1);
       int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
       if(c.getCellType() == CellType.Blank)
       {
         continue;
       }
        else{
       System.out.println(data);
            }
    }
    
    
    
    

For Apache POI version 3.x you can try below-

    for(int i = 1; i < rowCount; i++) {
       //getcell returns row num and starts from 1
       //Also my sheet column contains data in numeric form
       Cell cell  = sheet1.getRow(i).getCell(1);
       int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
       if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
       {
         continue;
       }
        else{
       System.out.println(data);
            }
    }

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