La seule façon de savoir avec certitude est de tester les lignes. Voici la solution que je utilise pour le même problème:
int lastRowIndex = -1;
if(sheet.getPhysicalNumberOfRows() > 0)
{
// getLastRowNum() actually returns an index, not a row number
lastRowIndex = sheet.getLastRowNum();
// now, start at end of spreadsheet and work our way backwards until we find a row having data
for(; lastRowIndex >= 0; lastRowIndex--){
Row row = sheet.getRow(lastRowIndex);
if(row != null){
break;
}
}
}
Note: cela ne vérifie pas pour les lignes qui semblent être vides, mais ne sont pas, comme les cellules qui ont une chaîne vide en eux. Pour cela, vous avez besoin d'une solution plus complète comme:
private int determineRowCount()
{
this.evaluator = workbook.getCreationHelper().createFormulaEvaluator();
this.formatter = new DataFormatter(true);
int lastRowIndex = -1;
if(sheet.getPhysicalNumberOfRows() > 0)
{
// getLastRowNum() actually returns an index, not a row number
lastRowIndex = sheet.getLastRowNum();
// now, start at end of spreadsheet and work our way backwards until we find a row having data
for(; lastRowIndex >= 0; lastRowIndex--)
{
Row row = sheet.getRow(lastRowIndex);
if(!isRowEmpty(row))
{
break;
}
}
}
return lastRowIndex;
}
/**
* Determine whether a row is effectively completely empty - i.e. all cells either contain an empty string or nothing.
*/
private boolean isRowEmpty(Row row)
{
if(row == null){
return true;
}
int cellCount = row.getLastCellNum() + 1;
for(int i = 0; i < cellCount; i++){
String cellValue = getCellValue(row, i);
if(cellValue != null && cellValue.length() > 0){
return false;
}
}
return true;
}
/**
* Get the effective value of a cell, formatted according to the formatting of the cell.
* If the cell contains a formula, it is evaluated first, then the result is formatted.
*
* @param row the row
* @param columnIndex the cell's column index
* @return the cell's value
*/
private String getCellValue(Row row, int columnIndex)
{
String cellValue;
Cell cell = row.getCell(columnIndex);
if(cell == null){
// no data in this cell
cellValue = null;
}
else{
if(cell.getCellType() != Cell.CELL_TYPE_FORMULA){
// cell has a value, so format it into a string
cellValue = this.formatter.formatCellValue(cell);
}
else {
// cell has a formula, so evaluate it
cellValue = this.formatter.formatCellValue(cell, this.evaluator);
}
}
return cellValue;
}
Il existe une raison pour laquelle toutes les classes de POI pour Excel sont appelées HSSF ... – ig0774