EasyExcel导入数据

使用EasyExcel进行导入数据有好多种方法,详情见https://www.yuque.com/easyexcel/doc
这里使用的是用监听器完成导入.
1.首先我们创建一个监听器,来进行读取数据并存入数据库

/**
 * <pre>
 * easyexcel 监听器
 * </pre>
 *
 * @author mc
 * @since 2022-05-16
 */
public class BzhdSystemConstructionImportListener extends AnalysisEventListener<BzhdSystemConstructionImport> {
    
    
    private static final Logger LOGGER = LoggerFactory.getLogger(BzhdSystemConstructionImportListener.class);
    /**
     * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<BzhdSystemConstructionImport> list = new ArrayList<BzhdSystemConstructionImport>();
 	/**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param demoDAO
     */
    private BzhdSystemConstructionMapper bzhdSystemConstructionMapper;

    public BzhdSystemConstructionImportListener(BzhdSystemConstructionMapper bzhdSystemConstructionMapper) {
    
    
        this.bzhdSystemConstructionMapper = bzhdSystemConstructionMapper;
    }

    @Override
    public void invoke(BzhdSystemConstructionImport bzhdSystemConstructionImport, AnalysisContext analysisContext) {
    
    
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(bzhdSystemConstructionImport));
        list.add(bzhdSystemConstructionImport);
        // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
        if (list.size() >= BATCH_COUNT) {
    
    
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    
    
        // 这里也要保存数据,确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成!");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
    
    
        LOGGER.info("{}条数据,开始存储数据库!", list.size());
            
        LOGGER.info("存储数据库成功!");
    }
}

2.controller层

    /**
     * 模板导入管理
     */
    @PostMapping("/import")
    @ApiOperation(value = "导入BzhdSystemConstruction对象", notes = "导入")
    public ApiResult<Boolean> importBzhdSystemConstruction(MultipartFile file) throws Exception {
    
    
        return bzhdSystemConstructionServiceImpl.importBzhdSystemConstruction(file);
    }

3.serviceiml层

    public ApiResult<Boolean> importBzhdSystemConstruction(MultipartFile file) {
    
    
        try{
    
    
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //easyexcel导入文件
            EasyExcel.read(inputStream, BzhdSystemConstructionImport.class,new BzhdSystemConstructionImportListener(bzhdSystemConstructionMapper)).sheet().doRead();
            return ApiResult.ok(true);
        }catch (IOException e){
    
    
            e.printStackTrace();
            return ApiResult.fail("数据异常无法导入文件!");
        }
    }

猜你喜欢

转载自blog.csdn.net/mcband/article/details/125247663