easyexcel导入
controller
@RequestMapping(value = "/read",method = RequestMethod.POST)
@ResponseBody
public String readExcel(@RequestParam("readExcel") MultipartFile file) {
try {
ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), ReadFile.class, new ExcelListener());
ExcelReaderSheetBuilder sheet = read.sheet();
sheet.doRead();
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
listener
package com.cat.youth_learning.Listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cat.youth_learning.mapper.YouthMapper;
import com.cat.youth_learning.pojo.ReadFile;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener<ReadFile> {
private final Integer MAX_LIST_SIZE=5;
List<ReadFile> list=new ArrayList<>();
publicExcelListener(YouthMapper youthMapper) {
this.youthMapper = youthMapper;
}
@Autowired
YouthMapper youthMapper;
@Override
public void invoke(ReadFile data, AnalysisContext context) {
list.add(data);
if (list.size()%MAX_LIST_SIZE==0){
savelist();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
savelist();
}
}
private void saveData() {
System.out.println(list.size()+"条数据,开始存储数据库!");
System.out.println(list);
}