easyExcel 公用-简洁【一个excel文档多个sheet 循环读取,适用简单表头】-导入

时间:2024-03-12 07:24:13
//监听器
@Slf4j
public class ExcelListener<T extends BaseRowModel> extends AnalysisEventListener<T> {
private final List<T> rows = new ArrayList<>();
private String departPro = "";
@Override
public void invoke(T object, AnalysisContext analysisContext) {
rows.add(object);
}

@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
log.info("read {} rows %n", rows.size());
}

public List<T> getRows() {
return rows;
}
}

//循环读取每一页,startNum 代表的是从第几行开始读ExcelUtil文件中
public static <T extends BaseRowModel> List<T> readExcel(final MultipartFile file,final Class<? extends BaseRowModel> clazz,int startNum) {
ExcelListener<T> listener = new ExcelListener<>();
try{
ExcelReader excelReader = EasyExcel.read(file.getInputStream()).build();
List<ReadSheet> readSheets = EasyExcel.read(file.getInputStream()).build().excelExecutor().sheetList();
if (!readSheets.isEmpty()) {
for (ReadSheet readSheet : readSheets) {
readSheet = EasyExcel.readSheet(readSheet.getSheetNo()).head(clazz).registerReadListener(listener).headRowNumber(startNum).build();
excelReader.read(readSheet);
}
}
excelReader.finish();
if (null == file.getInputStream()) {
throw new NullPointerException("the inputStream is null!");
}
}catch (Exception e){
log.error("读流出现异常:",e);
throw new BusinessException(BusinessCodeEnum.EXCEL_FILE_ILLEGA);
}
return listener.getRows();
}

//使用
List<User> list=ExcelUtil.readExcel(file,user.class,1);