这种读取数据的方式是将表格中所有不为空的sheet,row行都逐条读取,读取为List<list<String>>的格式又防止了数据的异常显示,再根据具体的业务需求对逐条的记录进行处理
public static List<List<String>> readExcel(MultipartFile file) throws IOException {
if (file == null){
throw new RuntimeException("文件流为空");
}
String format = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
Workbook workbook = null;
if (format.equals("xls")){
workbook = new HSSFWorkbook(file.getInputStream());
} else if (format.equals("xlsx")) {
workbook = new XSSFWorkbook(file.getInputStream());
} else {
throw new RuntimeException("文件类型错误!");
}
List<List<String>> result = new ArrayList<List<String>>();
int size = workbook.getNumberOfSheets();
// 循环每一页,并处理当前循环页
for (int numSheet = 0; numSheet < size; numSheet++) {
// Sheet 标识某一页
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
// 处理当前页,循环读取每一行
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
// Row表示行
Row row = sheet.getRow(rowNum);
if (row == null){
continue;
}
int minColIx = row.getFirstCellNum();
int maxColIx = row.getLastCellNum();
List<String> rowList = new ArrayList<String>();
// 遍历改行,获取处理每个cell元素
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
// Cell 表示单元格
Cell cell = row.getCell(colIx);
if (cell == null) {
continue;
}
rowList.add(getStringVal(cell));
}
result.add(rowList);
}
}
return result;
}
public static String getStringVal(Cell cell) {
switch (cell.getCellType()) {
case BOOLEAN:
return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
case FORMULA:
return cell.getCellFormula();
case NUMERIC:
cell.setCellType(STRING);
return cell.getStringCellValue();
case STRING:
return cell.getStringCellValue();
default:
return "";
}
}
EXCEL文件解析备忘录(03.07通用哦)
最新推荐文章于 2024-03-19 15:01:06 发布
本文介绍了一种高效读取Excel文件的方法,通过Java代码实现,能够处理多种格式(xls和xlsx),并能读取所有非空sheet和row行的数据,最终以List<List<String>>的形式返回,方便进一步的数据处理和分析。
507

被折叠的 条评论
为什么被折叠?



