栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

EasyExcel导入数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

EasyExcel导入数据

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

public class BzhdSystemConstructionImportListener extends AnalysisEventListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(BzhdSystemConstructionImportListener.class);
    
    private static final int BATCH_COUNT = 5;
    List list = new ArrayList();
 	
    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();
        }
    }

    
    @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 importBzhdSystemConstruction(MultipartFile file) throws Exception {
        return bzhdSystemConstructionServiceImpl.importBzhdSystemConstruction(file);
    }

3.serviceiml层

    public ApiResult 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("数据异常无法导入文件!");
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号