关于POI导入判断行与列是否为空sheet.getRow(),row.getCell()

问题:

项目中导入excel代码中遇到一个坑,代码如下:

for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
        CreateDeviceRequest request = new CreateDeviceRequest();
        Row row = sheet.getRow(rowIndex);
        // 如果这一行完全为空,则直接跳过,不计入成功或失败总数
        if (row == null) {
          continue;
        }
        for (int cellIndex = 0; cellIndex <= titleRow.getLastCellNum(); cellIndex++) {
          if (row.getCell(cellIndex) == null) {
            continue;
          }
        }
      }

以上判断行,列为空的代码不够严谨(row == null,row.getCell(cellIndex) == null),因为excel版本不同,返回值也不相同,经测试,部分返回null,但也有返回如下图结果的。
关于POI导入判断行与列是否为空sheet.getRow(),row.getCell()_第1张图片具体原因没有深研究。

解决方案:

for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
        DeviceStorage deviceStorage = new DeviceStorage();
        Row row = sheet.getRow(rowIndex);
        // 如果这一行完全为空,则直接跳过,不计入成功或失败总数
        if (isEmptyRow(row)) {
          continue;
        }
        for (int cellIndex = 0; cellIndex <= titleRow.getLastCellNum(); cellIndex++) {
          Cell cell = row.getCell(cellIndex);
          if (cell == null || cell.getCellType() == CellType.BLANK) {
            continue;
          }
        }
      }
 /**
   * Checks if a {@code Row} is {@code null}, empty or all cells in this row are blank.
   * @param row
   * @return
   */
  @SuppressWarnings("deprecation")
  public static boolean isEmptyRow(Row row) {
    if (row == null || row.toString().isEmpty()) {
      return true;
    } else {
      Iterator<Cell> it = row.iterator();
      boolean isEmpty = true;
      while (it.hasNext()) {
        Cell cell = it.next();
        if (cell.getCellType() != CellType.BLANK) {
          isEmpty = false;
          break;
        }
      }
      return isEmpty;
    }
  }

备注:

网上大部分都是4.0以下的判断单元格是否为空如下:

cell != null || cell.getCellType() != Cell.CELL_TYPE_BLANK(这个方法在4.0以后已经被废弃了)

最新的应该是cell.getCellType() !=CellType.BLANK

你可能感兴趣的:(项目,java,poi,excel)