关于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,但也有返回如下图结果的。
并不等于null具体原因没有深研究。

解决方案:

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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值