使用Apache POI库时无法读取连续的所有单元格值

时间:2015-03-31 07:51:36

标签: java apache apache-poi

我在连续迭代所有单元格时遇到问题,我能够正确地读取前4个单元格,所有单元格都为null。任何帮助赞赏 //以下是我正在使用的代码

InputStream is = new FileInputStream(new File(fileName));
    Workbook workbook = new XSSFWorkbook(is);
    int numberOfSheets = workbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
      Sheet sheet = workbook.getSheetAt(i);
      String name = sheet.getSheetName();
      if (name.equals(sheetName)) {
        Iterator<Row> rowItr = sheet.rowIterator();
        while (rowItr.hasNext()) {
          Row eachRow = rowItr.next();
          QuestionObjBuilder builder = new QuestionObjBuilder();
          Iterator<Cell> cellItr = eachRow.cellIterator();
          int index = 1;
          while (cellItr.hasNext()) {
            Cell eachCell = cellItr.next();
            int cellType = eachCell.getCellType();
            String label = "";
            if (cellType == Cell.CELL_TYPE_STRING) {
              label = eachCell.getStringCellValue();
            } else if (cellType == Cell.CELL_TYPE_NUMERIC) {
              int value = (int) eachCell.getNumericCellValue();
              label = String.valueOf(value);
            }
            builder = builder.set(index, label);
            index++;
            if (index > 10) {
              break;
            }
          }
        }
      }

    }
    workbook.close();

1 个答案:

答案 0 :(得分:0)

如果您的目标是从excel中读取所有单元格,则可以使用此代码

FileInputStream fileInputStream = new FileInputStream(fileName);
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet worksheet = workbook.getSheet(sheetName);

        Iterator<Row> it = worksheet.rowIterator();
        while(it.hasNext()){
            HSSFRow r = (HSSFRow) it.next();
            Iterator<Cell> it1=r.cellIterator();
            while(it1.hasNext()){
                HSSFCell cell = (HSSFCell)it1.next();
                System.out.println("Row: "+cell.getRowIndex()+" ,Column: "+cell.getColumnIndex());
                System.out.println(cell);
            }
            System.out.println();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }