读取excel赋值到ExcelEntity:
@Data
public class ExcelEntity extends BaseRowModel {
@ExcelProperty(index = 0, value = "警种名称")
private String policeName;
@ExcelProperty(index = 1, value = "警种类别")
private String typeName;
}
解析监听器:
/** 解析监听器,
* 每解析一行会回调invoke()方法。
* 整个excel解析结束会执行doAfterAllAnalysed()方法
*
* 下面只是我写的一个样例而已,可以根据自己的逻辑修改该类。
*/
public class ExcelListener extends AnalysisEventListener {
//自定义用于暂时存储data。
//可以通过实例获取该值
private List<Object> datas = new ArrayList<Object>();
public void invoke(Object object, AnalysisContext context) {
System.out.println("当前行:"+context.getCurrentRowNum());
System.out.println(object);
datas.add(object);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
doSomething(object);//根据自己业务做处理
}
private void doSomething(Object object) {
ExcelEntity excel = (ExcelEntity) object;
//1、入库调用接口
}
public void doAfterAllAnalysed(AnalysisContext context) {
// datas.clear();//解析结束销毁不用的资源
}
public List<Object> getDatas() {
return datas;
}
public void setDatas(List<Object> datas) {
this.datas = datas;
}
}
@Controller
@Slf4j
public class ExcelEntityUtil {
@Resource
private PoliceDictServiceImpl policeDictService;
@Resource
private DjOrganMapper djOrganMapper;
@GetMapping("do")
public void policeDictSave() {
FileInputStream fis = null;
List<PoliceDict> policeDictList = new ArrayList<>();
List<String> failName = new ArrayList<>();
try {
fis = new FileInputStream("D:\\2008.xlsx");
EasyExcel.read(fis, ExcelEntity.class, new AnalysisEventListener<ExcelEntity>() {
// 每解析一行数据,该方法会被调用一次
@Override
public void invoke(ExcelEntity excelEntity, AnalysisContext analysisContext) {
System.out.println("解析数据为:" + excelEntity.toString());
DjOrgan djOrgan = djOrganMapper.selectOne(new QueryWrapper<DjOrgan>().eq("name", excelEntity.getPoliceName()));
if (djOrgan == null) {
failName.add(excelEntity.getPoliceName());
} else {
PoliceDict policeDict = new PoliceDict()
.setPoliceId(djOrgan.getId())
.setName(excelEntity.getTypeName())
.setCreateTime(new Date())
.setExist(0);
policeDictList.add(policeDict);
}
}
// 全部解析完成被调用
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
log.info("解析完成...");
// 可以将解析的数据保存到数据库
policeDictService.saveBatch(policeDictList);
log.error("匹配失败:" + failName);
}
}).sheet().doRead();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}