easyExcel的使用案例

    • 引入easyExcel的jar包
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>2.0.5</version>
    </dependency>
    
    • 编写Execl类:ImportStaffInfoListBO
    @Data
    public class ImportStaffInfoListBO {
    
        @ExcelProperty("员工姓名")
        private String username;
    
        @ExcelProperty("性别")
        private String gender;
    
        @ExcelProperty("身份证号(唯一)")
        private String idCard;
    
        @ExcelProperty("手机号码")
        private String phoneNo;
    
        @ExcelProperty("合同起始日期")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private String contractStartDate;
    
        @ExcelProperty("合同终止日期")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private String contractEndDate;
    
        @ExcelProperty("试用期限")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private String probationDate;
    
        @ExcelProperty("岗位")
        private String position;
    
        @ExcelProperty("公积金账号")
        private String providentFundAccount;
    
        @ExcelProperty("社保账号")
        private String socialSecurityAccountNumber;
    
        @ExcelProperty("现居住地址")
        private String currentAddress;
    
        @ExcelProperty("户籍地址")
        private String permanentAddress;
    
        @ExcelProperty("紧急联系人姓名")
        private String emergencyContactName;
    
        @ExcelProperty("紧急联系人电话")
        private String emergencyContactPhoneNo;
    
        @ExcelProperty("银行卡号")
        private String bankCardNo;
    
        @ExcelProperty("银行卡持卡人姓名")
        private String bankCardHolderName;
    
        @ExcelProperty("银行卡开户支行")
        private String accountOpeningSubBranchName;
    
        @ExcelProperty("是否已婚;0未婚1已婚")
        private String marriageStatus;
    
        @ExcelProperty("学历")
        private String education;
    
        @ExcelProperty("签约主体")
        private String signTopic;
    
        @ExcelProperty("合同类型")
        private String contractType;
    
        @ExcelProperty("所属客户id")
        private Integer belongCustomerId;
    
        @ExcelProperty("所属客户名")
        private String belongCustomerName;
    
        @ExcelProperty("创建人")
        private String createBy;
    }
    
    • 监听器类:AnalysisEventListener
    /**
     * 有个很重要的点 DemoDataListener 不能被spring管理,
     * 要每次读取excel都要new,如果用到spring可以构造方法传进去
     *
     * @author liukang
     */
    
    public class StaffInfoDataListener extends AnalysisEventListener<ImportStaffInfoListBO> {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(StaffInfoDataListener.class);
    
        /**
         * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
         */
        private static final int BATCH_COUNT = 5;
    
        /**
         * 数据列表
         */
        private List<ImportStaffInfoListBO> importStaffInfoListBOList = new ArrayList<>();
    
        private StaffService staffService;
    
        public StaffInfoDataListener(StaffService staffService) {
            this.staffService = staffService;
        }
    
        /**
         * 每从excel文件中解析一条数据都会调用一次该方法
         *
         * @param importStaffInfoListBO
         * @param context
         */
    
        @Override
        public void invoke(ImportStaffInfoListBO importStaffInfoListBO, AnalysisContext context) {
    
            LOGGER.info("解析到一条数据:{}", JSON.toJSONString(importStaffInfoListBO));
    
            importStaffInfoListBOList.add(importStaffInfoListBO);
            // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
            if (importStaffInfoListBOList.size() >= BATCH_COUNT) {
                // 保存数据
                this.saveStaffInfoListData();
                // 存储完成清理 list
                importStaffInfoListBOList.clear();
            }
        }
    
        /**
         * 当所有数据解析完成了 都会来调用
         *
         * @param context
         */
    
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 这里调用是因为当总条数不是BATCH_COUNT倍数时,最后少于5条的数据也要保存(比如23条,前20条被解析保存了,最后3条也解析了,但是这需要在保存)
            saveStaffInfoListData();
            LOGGER.info("所有数据解析完成!");
    
        }
    
        private void saveStaffInfoListData() {
            LOGGER.info("{}条数据,开始存储数据库!", importStaffInfoListBOList.size());
            if (!CollectionUtils.isEmpty(importStaffInfoListBOList)) {
             	// 调用mapper接口进行保存
     		   staffService.saveBatchStaffInfo(importStaffInfoListBOList);
            }
        }
    
    }
    
    • 开始导入
    EasyExcel
        .read(excelInputStream,ImportStaffInfoListBO.class,new StaffInfoDataListener(this.staffService))
        .sheet()
        .doRead();
    

参考官网:easyExcel的使用

posted @ 2021-12-14 22:31  永无八哥  阅读(220)  评论(0编辑  收藏  举报