List<List<String>> result = new ArrayList<List<String>>();
InputStream is = file.getInputStream();
Workbook book = new HSSFWorkbook(is);
Sheet sheet = book.getSheetAt( 0 );
// 遍历行
Row row = null ;
int rowCnt = 0 ;
while ((row = sheet.getRow(rowCnt++)) != null ){
     List<String> rowData = new ArrayList<String>();
     int colCnt = 0 ;
     Cell cell = null ;
     while ((cell = row.getCell(colCnt++)) != null ){
         // 获取单元格的值
         String data = getCellValue(cell);
         if (filter != null ){
             data = filter.filter(rowCnt, colCnt, data, cell);
         }
         rowData.add(data);
     }
     result.add(rowData);
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
List<List<String>> result = new ArrayList<List<String>>();
InputStream is = file.getInputStream();
Workbook book = new HSSFWorkbook(is);
Sheet sheet = book.getSheetAt( 0 );
// 遍历行
Iterator<Row> rowItr = sheet.rowIterator();
 
while (rowItr.hasNext()) {
     List<String> rowData = new ArrayList<String>();
 
     // 遍历该行单元格
     Row row = rowItr.next();
     Iterator<Cell> cellItr = row.cellIterator();
     int col = 0 ;
     while (cellItr.hasNext()){
         Cell c = cellItr.next();
         
         // 获取单元格的值
         String data = getCellValue(c);
         if (filter != null ){
             data = filter.filter(col, data, c);
         }
         col++;
         rowData.add(data);
     }
     
     result.add(rowData);
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
List<List<String>> result = new ArrayList<List<String>>();
InputStream is = file.getInputStream();
Workbook book = new HSSFWorkbook(is);
Sheet sheet = book.getSheetAt( 0 );
// 遍历行
int rows = sheet.getLastRowNum();
for ( int i = 0 ; i < rows; i++){
     List<String> rowData = new ArrayList<String>();
     
     Row row = sheet.getRow(i);
     if (row != null ){
         int cols = row.getLastCellNum();
         for ( int j = 0 ; j < cols; j++){
             Cell cell = row.getCell(j);
             String data = getCellValue(cell);
             if (filter != null ){
                 data = filter.filter(i, j, data, cell);
             }
             rowData.add(data);
         }
     }
     result.add(rowData);
}

备注:前两种遍历方式对于存在空单元格或空行的excel文件解析得到的结果可能会出现错误,达不到预期结果。第一种poi认为空行通过sheet.getRow(index)得到的是null,所以while遍历无法完成所有行;第二种方式使用跌代器,存在的问题是,它只迭代非空单元格,空行或空单元格直接被无视;最后一种暴力遍历的方式,可以遍历所有的行,应该是可以信任的遍历方式了。
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐