通过Java读取excel文件.xlsx

时间:2016-03-19 04:16:49

标签: java excel apache-poi xssf

所以我的excel文件的大小相对较小。它包含8张。每张表都有我需要阅读的数据“记录”。每张表还有为跳过的标题保留的第一行;所以我的数据将从每张纸的第2行(第1个索引)开始,到最后一条记录结束。

所以,下面是我的代码来遍历工作表并读取每一行但是它无法读取每个工作表。而我似乎无法弄清楚为什么。请看看,任何建议将不胜感激。 谢谢!

FileInputStream fis = new FileInputStream(new File(filePath));
XSSFWorkbook wb = new XSSFWorkbook(fis);
DataFormatter formatter = new DataFormatter();

//iterate over sheets
for (int i=0; i<NUM_OF_SHEETS; i++) {
  sheet = wb.getSheetAt(i);
  sheetName = sheet.getSheetName();

  //iterate over rows
  for (int j=1; j<=lastRow; j++) {  //1st row or 0-index of each sheet is reserved for the headings which i do not need.
    row = sheet.getRow(j);
    if (row!=null) {
      data[j-1][0] = sheetName; //1st column or 0th-index of each record in my 2d array is reserved for the sheet's name.

      //iterate over cells
      for (int k=0; k<NUM_OF_COLUMNS; k++) {
        cell = row.getCell(k, XSSFRow.RETURN_BLANK_AS_NULL);
        cellValue = formatter.formatCellValue(cell); //convert cell to type String
        data[j-1][k+1] = cellValue;
      }//end of cell iteration
    }
  }//end of row iteration
}//end of sheet iteration
wb.close();
fis.close();

1 个答案:

答案 0 :(得分:2)

至少有一个很大的逻辑错误。由于您要将所有工作表的数据放在一个数组中,因此该数组的大小必须如下:

String[][] data = new String[lastRow*NUM_OF_SHEETS][NUM_OF_COLUMNS+1];

然后分配必须如下:

...
      data[(j-1)+(i*lastRow)][0] = sheetName; //1st column or 0th-index of each record in my 2d array is reserved for the sheet's name.
...

...
        data[(j-1)+(i*lastRow)][k+1] = cellValue;
...

使用您的代码,第二张表中的分配将覆盖第一张表中的分配,因为j每张表的开头为1。