使用JAVA poi读取excel文件并忽略空单元格



我试图从包含空单元格的excel表中读取数据,请考虑以下代码:

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);
}

但是,我的代码也读取空单元格,并将值显示为0(单元格具有数值(。如何使脚本中已填充的单元格为只读,并在忽略空单元格的同时显示这些单元格?

提前感谢

只需使用if条件更新for循环,该条件将检查从Cell中检索到的值。PFB为循环更新。

对于Apache POI 4.x版本,您可以尝试以下内容-

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);
}
}




对于Apache POI 3.x版本,您可以尝试以下内容-

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);
}
}

最新更新