本文主要是介绍POI解析Excel【poi的坑——空行处理】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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);
}
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);
}
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遍历无法完成所有行;第二种方式使用跌代器,存在的问题是,它只迭代非空单元格,空行或空单元格直接被无视;最后一种暴力遍历的方式,可以遍历所有的行,应该是可以信任的遍历方式了。
这篇关于POI解析Excel【poi的坑——空行处理】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!