easyExcel版本 2.2.10 内嵌poi版本 3.17 通用Listener
1. listener:
public class ExcelListener<T> extends AnalysisEventListener<T> {
private Map<String, Object> param;
private static final Logger logger = LoggerFactory.getLogger(ExcelListener.class);
/**
* 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 3000;
/**
* 缓存的数据
*/
private List<T> list = new ArrayList<>(BATCH_COUNT);
/**
* 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
*/
private SaveInterface<T> saveInterface;
/**
* 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param saveInterface
*/
public ExcelListener(SaveInterface<T> saveInterface,Map<String, Object> param) {
this.saveInterface = saveInterface;
this.param = param;
}
/**
* 这个每一条数据解析都会来调用
*
* @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(T data, AnalysisContext context) {
logger.info("解析到一条数据:{}", JSON.toJSONString(data));
list.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (list.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
list = new ArrayList<>(BATCH_COUNT);
}
}
/**
* 所有数据解析完成了 都会来调用
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
logger.info("所有数据解析完成!");
}
/**
* 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
*
* @param exception
* @param context
* @throws Exception
*/
@Override
public void onException(Exception exception, AnalysisContext context) {
logger.error("解析失败,但是继续解析下一行:{}", exception.getMessage());
// 如果是某一个单元格的转换异常 能获取到具体行号
// 如果要获取头的信息 配合invokeHeadMap使用
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
//todo 此处应抛出异常关联前端提示语句
logger.error("第{}行,第{}列解析异常", excelDataConvertException.getRowIndex() + 1,
excelDataConvertException.getColumnIndex() + 1);
}
}
/**
* 加上存储数据库
*/
private void saveData() {
logger.info("{}条数据,开始存储数据库!", list.size());
saveInterface.save(list,param);
logger.info("存储数据库成功!");
}
}
2 Save:
public interface SaveInterface<T> {
void save(List<T> list, Map<String, Object> param);
}
public class ActCustGroupServiceImpl implements ActCustGroupService, SaveInterface<ActCustGroupEntity> {
@Resource
ActCustGroupMapper actCustGroupMapper;
@Resource
ActCustGroupServiceImpl actCustGroupService;
@Override
public int batchInsert(List<ActCustGroupEntity> list) {
return actCustGroupMapper.batchInsert(list);
}
@Override
public void readExcel(MultipartFile multipartFile,Map<String, Object> param) throws Exception{
try {
EasyExcel.read(multipartFile.getInputStream(),ActCustGroupEntity.class,new ExcelListener(actCustGroupService,param)).sheet().doRead();
} catch (IOException e) {
throw e;
}
}
@Override
public void save(List<ActCustGroupEntity> list, Map<String, Object> param) {
Integer configId = (Integer)param.get("configId");
List<ActCustGroupEntity> collect = list.stream().peek(s -> s.build(s,configId)).collect(Collectors.toList());
batchInsert(collect);
}
3 entity:
@Data
public class ActCustGroupEntity implements Serializable {
private Integer id;
/*关联配置id*/
private Integer actConfigId;
/*用户id*/
@ExcelProperty("客户号")
private String userId;
/*0-未知,1-男,2-女*/
@ExcelProperty(value = "性别",converter = CustomConverter.class)
private Integer sex;
/*年龄*/
@ExcelProperty(value = "年龄")
private String age;
/*首次注册年份*/
@ExcelProperty("注册年份")
private String firstRegYear;
/*身份证归属省份*/
@ExcelProperty("省份")
private String idCardProvinc;
/*首次注册渠道*/
@ExcelProperty("注册渠道")
private String firstRegChannel;
/*教育层次*/
@ExcelProperty("学历")
private String eduLevel;
/*职业*/
@ExcelProperty("职业")
private String profession;
/*近3个月新增借据*/
@ExcelProperty(value = "近三个月借据数")
private String threeMonthLoan;
/*近6个月新增借据*/
@ExcelProperty(value = "近6个月借据数")
private String sixMonthLoan;
/*历史总借据*/
@ExcelProperty(value = "历史总借据数")
private String sumLoan;
/*创建人id*/
private String creatorId;
/*创建人*/
private String creator;
/*创建时间*/
private Date createTime;
public ActCustGroupEntity build(ActCustGroupEntity actCustGroupEntity,Integer actConfigId){
UserBaseVo currentLoginUser = CurrentEnvironmentInfo.getCurrentLoginUser();
actCustGroupEntity.setCreatorId(currentLoginUser.getId());
actCustGroupEntity.setCreator(currentLoginUser.getUsername());
actCustGroupEntity.setActConfigId(actConfigId);
actCustGroupEntity.setCreateTime(new Date());
return actCustGroupEntity;
}
}