因为我们在录入excel时如果直接按delete键删除,POI会认为我们delete的这行是null,但是存在
那么在读取过程中,就会有行数干扰问题,导致报空指针异常
这里我是这么做的
int rowCount = sheet.getLastRowNum();
int rowNums = 0;
//这里是去除表格里的空行,防止行数干扰
for(int i = 1; i<rowCount; i++) {
XSSFRow row = sheet.getRow(i);
boolean rowEmpty = isRowNotEmpty(row);
if(null != row && rowEmpty && row.getFirstCellNum() > -1) {
rowNums++;
}
}
public static boolean isRowNotEmpty(XSSFRow row) {
if (StringUtil.isNotNull(row)) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
XSSFCell cell = row.getCell(c);
if (cell != null && cell.getCellType() != BLANK) {
return true;
}
}
}
return false;
}
备注:这里的BLANK记得引入
import static org.apache.poi.ss.usermodel.CellType.BLANK;
//获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
for (int row = 1; row <= rowNums/*lastRowNum*/; row++) {
//这里是为了强制读30列,防止客户不填
for (int rol = 0; rol < 30/*sheet.getRow(row).getLastCellNum()*/; rol++){
XSSFCell cell = sheet.getRow(row).getCell(rol);
if (StringUtil.isNotNull(cell)) {
cell.setCellType(CellType.STRING);
}
fileContent.append((StringUtil.isNotNull(cell)? cell : "0") + ((rol+1)%30 == 0 ? "\n" : ","));
}
}