// 獲取准確的文件行數
public Sheet getAccuracyContextNum(XSSFSheet sheet) {
// 刪除空行
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
// 刪除空行
if (this.isRowEmpty(row)) {
int lastRowNum = sheet.getLastRowNum();
if (i >= 0 && i < lastRowNum) {
sheet.shiftRows(i + 1, lastRowNum, -1);// 將行號為i+1一直到行號為lastRowNum的單元格全部上移一行,以便刪除i行
}
if (i == lastRowNum) {
if (row != null) {
sheet.removeRow(row);
}
}
i--;
}
}
return sheet;
}
// 判斷行是否為空
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != CellType.BLANK) {
return false;
}
}
return true;
}
改進:刪除sheet后面的空行
public Sheet getAccuracyContextNum(XSSFSheet sheet) {
// 刪除空行
for (int i = sheet.getLastRowNum(); i >= 0; i--) {
Row row = sheet.getRow(i);
int c = row.getFirstCellNum();
Cell cell = row.getCell(c);
if (cell.getCellType() != CellType.STRING) {
sheet.removeRow(row);
} else {
break;
}
}
return sheet;
}
