POI解析Excel【poi的坑——空行处理】

List> result = new ArrayList>();
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 rowData = new ArrayList();
    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);
}

List> result = new ArrayList>();
InputStream is = file.getInputStream();
Workbook book = new HSSFWorkbook(is);
Sheet sheet = book.getSheetAt(0);
// 遍历行
Iterator rowItr = sheet.rowIterator();

while (rowItr.hasNext()) {
    List rowData = new ArrayList();

    // 遍历该行单元格
    Row row = rowItr.next();
    Iterator 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);
}

List> result = new ArrayList>();
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 rowData = new ArrayList();
    
    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遍历无法完成所有行;第二种方式使用跌代器,存在的问题是,它只迭代非空单元格,空行或空单元格直接被无视;最后一种暴力遍历的方式,可以遍历所有的行,应该是可以信任的遍历方式了。

你可能感兴趣的:(Java)