package com.panzhihua.common.listen; import java.util.ArrayList; import java.util.List; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.fastjson.JSONObject; import com.panzhihua.common.exceptions.ServiceException; import com.panzhihua.common.model.vos.R; import com.panzhihua.common.model.vos.community.ComCvtServeExcelVO; import com.panzhihua.common.service.community.CommunityService; import lombok.extern.slf4j.Slf4j; /** * @description: 便民服务导入监听 * @author: Null * @date: 2021/3/11 13:26 */ @Slf4j public class ComCvtServeExcelListen extends AnalysisEventListener { private static final int BATCH_COUNT = 5000; private CommunityService communityService; private Long communityId; private List list = new ArrayList<>(); public ComCvtServeExcelListen(CommunityService communityService, Long communityId) { this.communityService = communityService; this.communityId = communityId; } @Override public void invoke(ComCvtServeExcelVO comCvtServeExcelVO, AnalysisContext analysisContext) { list.add(comCvtServeExcelVO); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { log.info("excel导入数据【{}】", JSONObject.toJSONString(list)); R r = this.communityService.listSaveConvenientServeExcelVO(list, this.communityId); if (!R.isOk(r)) { throw new ServiceException(r.getMsg()); } // 清空list list.clear(); } } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { log.info("excel导入数据【{}】", JSONObject.toJSONString(list)); R r = this.communityService.listSaveConvenientServeExcelVO(list, this.communityId);// 确保最后遗留的数据保存在数据库中 if (!R.isOk(r)) { throw new ServiceException(r.getMsg()); } } /** * 在转换异常 * * @param exception * @param context * @throws Exception */ @Override public void onException(Exception exception, AnalysisContext context) throws ServiceException { log.error("抛出异常:{}", exception.getMessage()); if (exception instanceof ExcelDataConvertException) { ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception; log.error("第{}行,第{}列解析异常,数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData()); } else { throw new ServiceException(exception.getMessage()); } } }