EasyExcel 导入Excel文件,我的是内部类写法,没有监听器
依赖:
<!--easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
接口:
@PostMapping("/importExcel")
public AjaxResult importCarInfoInOutExcel(@RequestParam("file") MultipartFile file){
boolean b = gdCarinfoInoutStatisticsService.insertCarInfoInOutExcel(file);
if (b) {
return AjaxResult.success(b);
}
return AjaxResult.error("导入数据失败");
}
重写impl方法:
@Transactional(rollbackFor = Exception.class)
@Override
public boolean insertCarInfoInOutExcel(MultipartFile file) {
try (InputStream inputStream = file.getInputStream()) {
// 匿名内部类 不用额外写一个DemoDataListener
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(inputStream, GdCarinfoInoutStatistics.class, new ReadListener<GdCarinfoInoutStatistics>() {
//500条清理一次,需要注意的是这个写法有bug500或者500的倍数的数据会报错
public static final int BATCH_COUNT = 500;
private List<GdCarinfoInoutStatistics> dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
//这个每一条数据解析都会来调用
@Override
public void invoke(GdCarinfoInoutStatistics data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
Date nowDate = DateUtils.getNowDate();
data.setInoutStatisticsId(IdUtils.randomUUID());
data.setCreateAuthor(getUsername());
data.setUpdateAuthor(getUsername());
data.setCreateTime(nowDate);
data.setUpdateTime(nowDate);
boolean exists = gdCarinfoInoutStatisticsMapper.selectCarinfoInoutStatistics(data);
if (!exists){
dataList.add(data);
if (dataList.size() >= BATCH_COUNT) {
saveData();
dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
//加上存储数据库,只保留一个月的数据
private void saveData() {
log.info("{}条数据,开始存储数据库!", dataList.size());
gdCarinfoInoutStatisticsMapper.batchInsertCarInfoInOut(dataList);
log.info("存储数据库成功!");
// 检查数据库中的记录数量
int count = gdCarinfoInoutStatisticsMapper.countRecords();
while (count > 31) {
// 删除最早的记录
gdCarinfoInoutStatisticsMapper.deleteEarliestRecord();
// 重新计算记录数量
count = gdCarinfoInoutStatisticsMapper.countRecords();
}
}
}).headRowNumber(1).sheet().doRead();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return true;
}