private static HashMap<String, ArrayList<String[]>> analysisFile(MultipartFile file) throws IOException {
HashMap<String, ArrayList<String[]>> hashMap = new HashMap<>();
String msg = "";
// 获取workbook对象
Workbook workbook = null;
String filename = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
// 根据后缀名是否excel文件
if (filename.endsWith("xls")) {
// 2003版本
workbook = new HSSFWorkbook(inputStream);
} else if (filename.endsWith("xlsx")) {
// 2007版本
workbook = new XSSFWorkbook(inputStream);
}
// 创建arrayList,把每一行作为一个String数组,存到集合中
ArrayList<String[]> arrayList = new ArrayList<>();
if (workbook != null) {
// 只解析第一个sheet
Sheet sheet = workbook.getSheetAt(0);
if (sheet == null) {
hashMap.put("Excel文件为空!", arrayList);
return hashMap;
}
// 默认第一行为标题栏,从第二行开始解析
int firstRowNum = 1;
// 获取sheet中数据的总行数
int lastRowNum = sheet.getPhysicalNumberOfRows();
// 获取列数。默认第一行为0
short firstCellNum = 0;
// 获取标题栏的总列数
int lastCellNum = sheet.getRow(0).getPhysicalNumberOfCells();
// 循环每一行
for (int rowNum = firstRowNum; rowNum < lastRowNum; rowNum++) {
// 获取当前行
Row row = sheet.getRow(rowNum);
String[] strings = new String[lastCellNum];
// 循环当前行的每一列
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
if (cell == null || "".equals(cell) || cell.getCellType() == CellType.BLANK) {
msg = msg + "第" + (rowNum + 1) + "行,第" + (cellNum + 1) + "列为空;";
}
String cellValue = "";
cellValue = getCellValue(cell);
strings[cellNum] = cellValue;
}
arrayList.add(strings);
}
}
inputStream.close();
hashMap.put(msg, arrayList);
return hashMap;
}