I’m trying to read data from excel using POI. How can I check if that is an empty cell?
I don’t know what is missing I think this should be working:
java.util.Iterator<Row> rows = worksheet.rowIterator();
HSSFRow row = (HSSFRow) rows.next();
HSSFCell cellF1 = (HSSFCell) row.getCell(5);
if(cellF1.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
String val = "";
}
I got error in if statement (null pointer), but only if I use this I can check that:
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
java.util.Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
if(cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
String emptytype = "";
System.out.println("empty");
}
}
}
This is normal behavior for the 1-argument version of
Row.getCell. If you look at the API doc, it specifically states thatgetCellwill return null if the cell is not defined. Many java functions exhibit this sort of behavior, so there is nothing wrong with coding to take this into account. So, one version of your code could be something like:Alternatively, you could use the other version of
Row.getCell, which takes a second argument that specifies the missing cell policy. This version would allow you to specify thatgetCellreturn a null cell for blank cells. So, here is some althernative code:Or, if you prefer, you could specify the policy as
Row.CREATE_NULL_AS_BLANK. In that case, you would replaceif (cell != null)withif (cell.getCellType() != Cell.CELL_TYPE_BLANK).