1.引入依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-extension -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.1</version>
</dependency>
2.前端调用后端接口
3.后端创建接口
@Autowired
private SubjectService subjectService;
@ApiOperation(value = "excel批量导入")
@PostMapping("/addSubject")
public Msg addSubject(MultipartFile file){
subjectService.saveSubject(file,subjectService);
return Msg.success();
}
3.1创建实体类
@Data
public class ExcelSubjectData {
@ExcelProperty(index = 0)
private String oneSubjectName;
@ExcelProperty(index = 1)
private String twoSubjectName;
}
3.2调用service层
public interface SubjectService extends IService<Subject> {
void saveSubject(MultipartFile file,SubjectService subjectService);
}
3.3实现service层
@Override
public void importSubjectData(MultipartFile file,EduSubjectService subjectService) {
try {
InputStream inputStream = file.getInputStream();
EasyExcel.read(inputStream, ExcelSubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
}catch(Exception e) {
e.printStackTrace();
throw new GuliException(20002,"添加课程分类失败");
}
}
4.创建Excel监听器
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {
public SubjectService subjectService;
public SubjectExcelListener() {
}
public SubjectExcelListener(SubjectService subjectService) {
this.subjectService = subjectService;
}
@Override
public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
if (excelSubjectData == null){
throw new GuliException(20001,"文件数据为空");
}
Subject subject = this.existOneSubject(subjectService, excelSubjectData.getOneSubjectName());
if (subject == null){
subject =new Subject();
subject.setParentId("0");
subject.setTitle(excelSubjectData.getOneSubjectName());
subjectService.save(subject);
}
String pid =subject.getId();
Subject subject2 = this.existTwoSubject(subjectService, excelSubjectData.getTwoSubjectName(), pid);
if(subject2 == null){
subject2 =new Subject();
subject2.setParentId(pid);
subject2.setTitle(excelSubjectData.getTwoSubjectName());
subjectService.save(subject2);
}
}
private Subject existOneSubject(SubjectService subjectService,String name){
QueryWrapper<Subject> wrapper =new QueryWrapper<>();
wrapper.eq("title", name);
wrapper.eq("parent_id", "0");
Subject one = subjectService.getOne(wrapper);
return one;
}
private Subject existTwoSubject(SubjectService subjectService,String name,String pid){
QueryWrapper<Subject> wrapper =new QueryWrapper<>();
wrapper.eq("title", name);
wrapper.eq("parent_id", pid);
Subject one = subjectService.getOne(wrapper);
return one;
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}