controller
@RequestMapping("/importExcelFile")
public BaseResponse importExcelFile(@RequestParam("file") MultipartFile uploadFile) {
return new BaseResponse().success(excelService.importExcelFile(uploadFile));
}
Service
public BaseResponse importExcelFile (MultipartFile uploadFile){
try {
if(uploadFile.isEmpty()){
return new BaseResponse().error("文件为空,初始化失败");
}
if (orgService.getTotalRecordCount() == 0 ){
ExcelReaderBuilder workBook = EasyExcel.read
(uploadFile.getInputStream(), TbOrganization.class, new ExcelListener());
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
sheet1.doRead();
List<TbOrganization> orgList = ExcelListener.getOrgList();
List<String> collect1 = orgList.stream().map(TbOrganization::getName).distinct().collect(Collectors.toList());
if(collect1.size()!=orgList.size()){
return new BaseResponse().error("excel表内的名称有重复,初始化失败");
}
for(TbOrganization org : orgList) {
orgService.addOrg(org);
}
return new BaseResponse().success("初始化成功");
}else{
return new BaseResponse().error("数据库非空,无法使用初始化方法");
}
} catch (Exception e) {
System.out.println("导入失败:" + e.getMessage());
return new BaseResponse().error("导入失败");
}
}
注:这里我的需求时只能使用excel导入初始化,如果表中有数据就无法导入,且excel表中的名称字段不能重复。
ExcelListener:
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener<TbOrganization> {
public static List<TbOrganization> orgList = new ArrayList<>();
@Override
public void invoke(TbOrganization tbOrganization, AnalysisContext analysisContext) {
orgList.add(tbOrganization);
System.out.println("解析到一条数据:" + tbOrganization);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("全部解析完成");
}
public static List<TbOrganization> getOrgList() {
return orgList;
}
}
import com.alibaba.excel.annotation.ExcelProperty;
import java.io.Serializable;
public class TbOrganization implements Serializable {
//主键
private Long id;
@ExcelProperty("id")
private String idName;
@ExcelProperty("name")
private String name;
@ExcelProperty("code")
private String code;
///。。。。。。其他。。。。。。
}