如果您能看到,并且有更好的方法希望不吝赐教
private void getDataFromExcel() throws InvalidFormatException, IOException {
String fileName = "Excel文件.xlsx";
String filePath = "E://testExcel";
File file = new File(filePath, fileName);
if (file.exists()) {
XSSFWorkbook workBook = new XSSFWorkbook(file);
XSSFSheet sheet = workBook.getSheet("员工表");
XSSFRow row = sheet.getRow(0);
String[] rowData = new String[row.getLastCellNum()];
// 缓存excel表中表头所对应的序号, 用于给bean的对用属性赋值
Integer[] numberArray = new Integer[row.getLastCellNum()];
// 参照表头
String[] titleArray = new String[] { "员工卡号", "员工姓名", "员工年龄", "员工薪资", "所在部门" };
for (int i = 0; i < row.getLastCellNum(); i++) {
rowData[i] = row.getCell(i).getStringCellValue();
}
// 将获取的表头放入list中,便于获取excel中表头与参照表头所对应的数组下标
List<String> numberList = new ArrayList<>();
for (String str : rowData) {
numberList.add(str);
}
// 根据参照表头的内容获取excel动态表头所对应的下标
for (int i = 0; i < numberList.size(); i++) {
numberArray[i] = numberList.indexOf(titleArray[i]);
}
Arrays.stream(rowData).forEach(System.out::print);
List<EmpModel> excelUserList = new ArrayList<>();
for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
XSSFRow rowUserData = sheet.getRow(i);
String[] rowDataArray = new String[row.getLastCellNum()];
for (int j = 0; j < rowUserData.getLastCellNum(); j++) {
XSSFCell cell = rowUserData.getCell(j);
rowDataArray[j] = cell.getStringCellValue();
}
EmpModel userModel = new EmpModel();
userModel.setId(rowDataArray[numberArray[0]]);
userModel.setName(rowDataArray[numberArray[1]]);
userModel.setAge(Integer.parseInt(rowDataArray[numberArray[2]]));
userModel.setSalary(Double.parseDouble(rowDataArray[numberArray[3]]));
userModel.setDepartNm(rowDataArray[numberArray[4]]);
excelUserList.add(userModel);
}
excelUserList.stream().forEach(System.out::println);
workBook.close();
} else {
System.out.println("文件不存在");
}
}