How I can determine empty rows in .xls documents using Apache POI?
The row iterator returns only rows that contain data, however if they are completely empty then iterating by row index, getRow(index)
returns null
Solution:
Up to POI version 3.14 (thanks to Sergii Lisnychyi):
private boolean checkIfRowIsEmpty(Row row) {
if (row == null) {
return true;
}
if (row.getLastCellNum() <= 0) {
return true;
}
for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
Cell cell = row.getCell(cellNum);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && StringUtils.isNotBlank(cell.toString())) {
return false;
}
}
return true;
}
From POI version 3.15 to 4.2 (int getCellType()
is deprecated):
private boolean checkIfRowIsEmpty(Row row) {
if (row == null) {
return true;
}
if (row.getLastCellNum() <= 0) {
return true;
}
for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
Cell cell = row.getCell(cellNum);
if (cell != null && cell.getCellTypeEnum() != CellType.BLANK && StringUtils.isNotBlank(cell.toString())) {
return false;
}
}
return true;
}
From POI version 4 (CellTypeEnum getCellTypeEnum()
will return the Enum not int):
private boolean checkIfRowIsEmpty(Row row) {
if (row == null) {
return true;
}
if (row.getLastCellNum() <= 0) {
return true;
}
for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
Cell cell = row.getCell(cellNum);
if (cell != null && cell.getCellTypeEnum() != CellType.BLANK && StringUtils.isNotBlank(cell.toString())) {
return false;
}
}
return true;
}
try using if(iterator.hasNext)
Row nextRow = null;
Cell nextCell = null;
Iterator<Row> iterator = firstSheet.rowIterator();
if(iterator.hasNext) {
return true;
}
else {
return false;
}
Assuming you want to check if row n
is empty, remembering that rows in Apache POI are zero based not one based, you'd want something like:
Row r = sheet.getRow(n-1); // 2nd row = row 1
boolean hasData = true;
if (r == null) {
// Row has never been used
hasData = false;
} else {
// Check to see if all cells in the row are blank (empty)
hasData = false;
for (Cell c : r) {
if (c.getCellType() != Cell.CELL_TYPE_BLANK) {
hasData = true;
break;
}
}
}