EasyExcel版本
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
定义Listener
public class ExcelUtils {
public static void readExcel(InputStream inputStream, List<DataListener> listData) {
ExcelReader excelReader = EasyExcel.read(inputStream).build();
List<ReadSheet> listReadSheet = new ArrayList<>();
for (int i = 0; i < listData.size(); i++) {
ReadSheet readSheet1 = EasyExcel.readSheet(listData.get(i).sheetName)
.head(listData.get(i).classa)
.registerReadListener(listData.get(i)
).build();
listReadSheet.add(readSheet1);
}
excelReader.read(listReadSheet);
excelReader.finish();
}
}
使用
public List<EvaluateInfoEntity> uploadExcel(MultipartFile file, String evaluateMode) {
if (Objects.isNull(file)) {
throw new NtCloudBizException(500, "请选择要上传的文件");
}
if (StringUtils.isEmpty(evaluateMode)) {
throw new NtCloudException(ResultCode.PARAMETER_ERROR, "请选择评价模式");
}
//判断文件类型是否正确
String originalFilename = file.getOriginalFilename();
String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
if (!FILE_XLS.equalsIgnoreCase(fileType) && !FILE_XLSX.equalsIgnoreCase(fileType)) {
throw new NtCloudBizException(500, "上传的文件类型错误,只能上传xlsx,xls类型的文件");
}
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件开始
List<DataListener> listData = new ArrayList<>();
DataListener sheetListener1 = new DataListener<EvaluateInfoEntity>(EvaluateInfoEntity.class, "Sheet1");
DataListener sheetListener2 = new DataListener<DataImportEvaluateScoreEntity>(DataImportEvaluateScoreEntity.class, "Sheet2");
listData.add(sheetListener1);
listData.add(sheetListener2);
ExcelUtils.readExcel(inputStream, listData);
DataListener dataListener0 = listData.get(0);
// 获取第一个sheet页
List<EvaluateInfoEntity> evaluateInfoEntityList = dataListener0.getList();
DataListener dataListener1 = listData.get(1);
// 获取第二个sheet页
List<DataImportEvaluateScoreEntity> dataImportEvaluateScoreEntityList = dataListener1.getList();
}
// 读取文件开始
List<DataListener> listData = new ArrayList<>();
DataListener sheetListener1 = new DataListener<EvaluateInfoEntity>(EvaluateInfoEntity.class, "Sheet1");
DataListener sheetListener2 = new DataListener<DataImportEvaluateScoreEntity>(DataImportEvaluateScoreEntity.class, "Sheet2");
listData.add(sheetListener1);
listData.add(sheetListener2);
ExcelUtils.readExcel(inputStream, listData);
DataListener dataListener0 = listData.get(0);
List<EvaluateInfoEntity> evaluateInfoEntityList = dataListener0.getList();
DataListener dataListener1 = listData.get(1);
List<DataImportEvaluateScoreEntity> dataImportEvaluateScoreEntityList = dataListener1.getList();