1.自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelLead {
Class<? extends AnalysisEventListener> obj() default InitStockDataHandle.class;
int sheet() default 0;
Class zclass() default InitStockDataHandle.class;
}
2.自定义切面,需改请求参数
@Aspect
@Component
@Slf4j
public class ExcelLeadAspect {
@Pointcut("@annotation(com.annotation.ExcelLead)")
public void lead() {
}
@Around("lead()")
public Object parameter(ProceedingJoinPoint joinPoint) throws Throwable{
log.info("请求类方法:{}", joinPoint.getSignature().getName());
MultipartFile file = (MultipartFile)joinPoint.getArgs()[0];
if (file!=null){
Class clazz = joinPoint.getTarget().getClass();
Method methods = clazz.getMethod(joinPoint.getSignature().getName(),Object.class);
boolean annotationPresent = methods.isAnnotationPresent(ExcelLead.class);
if (annotationPresent) {
ExcelLead methodAnno = methods.getAnnotation(ExcelLead.class);
InitStockDataHandle analysisEventListener = null;
analysisEventListener = (InitStockDataHandle) methodAnno.obj().newInstance();
EasyExcel.read(file.getInputStream(), methodAnno.zclass(), analysisEventListener).sheet(methodAnno.sheet()).doRead();
joinPoint.getArgs()[0] = analysisEventListener.getValue();
return joinPoint.proceed(joinPoint.getArgs());
}
}
return null;
}
}
方法上添加注解
@ExcelLead(zclass = MaterialGroupFileDTO.class)
@ApiOperation("素材组文件导入")
@PostMapping("file-lead")
public ResponseBean fileLead(@RequestParam("file")Object object){
return new ResponseBean().success(xxxxService.fileLead(object));
}
注: 请求的方法必须是Object 类型
其他
@Slf4j
@NoArgsConstructor
public class InitStockDataHandle<T> extends AnalysisEventListener<T> {
private List<T> excelModelList = new ArrayList<>();
public InitStockDataHandle(InputStream inputStream,Class obj,int sheet){
EasyExcel.read(inputStream, obj, this).sheet(sheet).doRead();
}
@Override
public void invoke(T data, AnalysisContext context) {
log.info("解析了一条数据:{}", JSONObject.toJSONString(data));
excelModelList.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//解析完excel后自动执行此方法
log.info("开始处理数据");
}
public List<T> getValue(){
return excelModelList;
}
}