easyExcel导入 无模版 实体类导入 自定义表头 存入数据库

喜欢的点赞👍 不喜欢的解散 创作不易记得三连

开整

1 导入依赖

 <!--导出数据-->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>2.1.3</version>
 </dependency>

2.导入监听器

@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(NoModelDataListener.class);

    private IStandingBookMangerService iStandingBookMangerService;
    private String tabaleName;

    public NoModelDataListener(IStandingBookMangerService iStandingBookMangerService,String tabaleName) {
        this.iStandingBookMangerService = iStandingBookMangerService;
        this.tabaleName = tabaleName;
    }

    /**
     * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
     */
    private static final int BATCH_COUNT = 300;

    List<Map<String, Object>> addList = new ArrayList<>();
    List<Map<String, Object>> updateList = new ArrayList<>();

    /**
     * 存储Key
     */
    Map<Integer, String> key = new HashMap<>();
    /**
     * keuList
     */
    List<String> keyList=new ArrayList<>();

    /**
     * 重写invokeHeadMap方法,获去表头,如果有需要获取第一行表头就重写这个方法,不需要则不需要重写
     *
     * @param headMap Excel每行解析的数据为Map<Integer, String>类型,Integer是Excel的列索引,String为Excel的单元格值
     * @param context context能获取一些东西,比如context.readRowHolder().getRowIndex()为Excel的行索引,表头的行索引为0,0之后的都解析成数据
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        LOGGER.info("解析到一条头数据:{}, currentRowHolder: {}", headMap.toString(), context.readRowHolder().getRowIndex());
        Set<Integer> integerSet = headMap.keySet();
        for (Integer integer : integerSet) {
            keyList.add(headMap.get(integer));
        }
        key.putAll(headMap);
    }


    /**
     * 读取数据 筛选过滤数据 赛选出那些数据是添加 那些数据是修改
     * @param data 传入数据
     * @param context 读取数据
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        HashMap<String, Object> objectObjectHashMap = new HashMap<>(16);
        Set<Integer> integerSet = data.keySet();
        String id=null;
        for (Integer integer : integerSet) {
            String s = key.get(integer);
            if("id".equals(s)){
                id = data.get(integer);
                if (StringUtils.isNotBlank(id)) {
                    Double f = Double.valueOf(id);
                    Integer a = (int)Math.ceil(f);
                    objectObjectHashMap.put(s,a);
                }else {
                    objectObjectHashMap.put(s,null);
                }
            }else{
                objectObjectHashMap.put(s,data.get(integer));
            }

        }
        if (StringUtils.isBlank(id)) {
            addList.add(objectObjectHashMap);
        } else {
            updateList.add(objectObjectHashMap);
        }
        
        // 分批次 插入数据库 可以使用 暂时不适用 使用的 可以开启
        //list.add(data);
//        if (list.size() >= BATCH_COUNT) {
//            saveData();
//            list.clear();
//        }
    }

    /**
     * 读取完成后 保存数据
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成!");
    }
    
    /**
     * 加上存储数据库 添加 以及更新
     */
    private void saveData() {
        LOGGER.info("{}条数据,开始存储数据库!", addList.size());
        iStandingBookMangerService.addStandingBookBatch(addList,tabaleName,keyList);
        iStandingBookMangerService.updateStandingBookBatch(updateList,tabaleName);
        LOGGER.info("存储数据库成功!");
    }

    public List<Map<Integer, String>> getDatas() {
        return null;
    }

    public void setDatas(List<Map<Integer, String>> datas) {
        //this.list = datas;
    }

}

3.测试数据

/**
     * 导入数据
     *
     * @throws Exception
     */
    @GetMapping(value = "/importData")
    @ApiOperation(value = "导入数据", notes = "导入数据")
    public ApiResponse importData(MultipartFile file,@RequestParam String tableName) throws Exception {
        ApiResponse apiResponse = new ApiResponse();
        ApiResponse res = new ApiResponse();
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件的后缀名为xlsx
        String fileXlsx = fileName.substring(fileName.length() - 5);
        String fileXls = fileName.substring(fileName.length() - 4);

        //如果不是excel文件
        if (!(fileXlsx.equals(".xlsx") || fileXls.equals(".xls"))) {
            res.setErrorCode(400);
            res.setErrorMsg("文件格式错误");
            return res;
        }
        //初始化监听器
        NoModelDataListener noModelDataListener = new NoModelDataListener(iStandingBookMangerService, tableName);
        Map<String,Object> result = new HashMap<>();
        //解析数据
        List<Object> list = EasyExcel.read(file.getInputStream(),noModelDataListener).sheet(0).doReadSync();
        result.put("list", list);
        apiResponse.setErrorCode(200);
        return apiResponse;
    }

4.测试数据表

在这里插入图片描述

5 postman测试

在这里插入图片描述

7.mapper 如何解析

map 传过来的数据 mybatis 的 mapper.xml 如何解析 参考我的另外一篇博文

https://blog.youkuaiyun.com/Mclaughling/article/details/110137985

8.总结

后面有空在总结

可以使用easyexcel提供的监听器,基于SAX解析方式读取excel文件并将数据插入数据库中,无需使用实体类。以下是一个简单的例子: 首先,定义一个监听器类,继承自AnalysisEventListener: ``` public class ExcelListener extends AnalysisEventListener<Map<Integer, String>> { private List<Map<Integer, String>> dataList = new ArrayList<>(); @Override public void invoke(Map<Integer, String> rowData, AnalysisContext context) { // 将每行数据存入List中 dataList.add(rowData); // 每1000条数据执行一次插入操作 if (dataList.size() >= 1000) { saveData(); dataList.clear(); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { // 最后不足1000条的数据也要插入 if (!dataList.isEmpty()) { saveData(); dataList.clear(); } } private void saveData() { // 执行插入操作,将List中的数据插入数据库 } } ``` 然后,在代码中使用如下方式读取并解析excel文件: ``` InputStream inputStream = new FileInputStream("path/to/excel/file.xlsx"); ExcelListener listener = new ExcelListener(); ExcelReader excelReader = new ExcelReader(inputStream, null, listener); excelReader.read(); ``` 在读取excel文件时,需要传入一个InputStream对象,以及一个实现了AnalysisEventListener接口的监听器对象。在监听器的invoke方法中,每次解析到一行数据时,将其存入List中。当List中的数据达到一定数量时,执行一次插入操作。在doAfterAllAnalysed方法中,最后不足1000条的数据也要插入。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值