关于SpringBoot项目利用阿里EasyExcel快捷导入Excel文件入库初始化数据的简单实现

一、问题描述

无论新项目还是旧项目,都会出现数据维护、数据初始化等操作,手动录显然很low(领导会骂你),所以一般采用批量导入导出。这里你还在用原始读取excel逐行逐列去读取吗?2024了ok?利用工具是我们cv大师的一贯作风,so就学习一下EasyExcel吧。

二、实践步骤

2.1导入maven依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.1</version>
</dependency>

你可能会问,为什么是这个版本?版本的选择根据你SpringBoot的版本,我这里是2.x

2.2代码实践

2.2.1定义实体映射,也即Excel表头一行跟实体的映射,封装ImportDataListAO

java 复制代码
package com.juhe.digital.pojo.ao;

import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author kiki
 * @date 2024/7/24
 * @description
 */
@Data
public class ImportDataListAO {
    @ApiModelProperty(value = "一级分类")
    @ExcelProperty(value = "一级分类",index = 0)
    private String firstClassify;

    @ApiModelProperty(value = "二级分类")
    @ExcelProperty(value = "二级分类",index = 1)
    private String secondClassify;

    @ApiModelProperty(value = "数据资源项")
    @ExcelProperty(value = "数据资源项",index = 2)
    private String dataResourceItem;

    @ApiModelProperty(value = "汇入频率")
    @ExcelProperty(value = "汇入频率",index = 3)
    private String importFrequency;

    @ApiModelProperty(value = "汇入方式")
    @ExcelProperty(value = "汇入方式",index = 4)
    private String importMode;

    @ApiModelProperty(value = "源头部门")
    @ExcelProperty(value = "源头部门",index = 5)
    private String orgName;

    @ApiModelProperty(value = "业务处室")
    @ExcelProperty(value = "业务处室",index = 6)
    private String businessOffice;

    @ApiModelProperty(value = "联系人")
    @ExcelProperty(value = "联系人",index = 7)
    private String relationUser;

    @ApiModelProperty(value = "联系方式")
    @ExcelProperty(value = "联系方式",index = 8)
    private String relationMobile;

    @ApiModelProperty(value = "表")
    @ExcelProperty(value = "表",index = 9)
    private String dataTableName;

}

2.2.2定义监听器

java 复制代码
package com.juhe.digital.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.juhe.digital.pojo.ao.ImportDataListAO;
import com.juhe.digital.service.IDataListInfoService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author kiki
 * @date 2024/7/23
 * @description
 */
@Slf4j
public class DataListInfoAOListener extends AnalysisEventListener<ImportDataListAO> {

    private static final int BATCH_COUNT = 5;

    private IDataListInfoService dataListInfoService;

    private List<ImportDataListAO> cachedDataList = ListUtils.newArrayListWithCapacity(BATCH_COUNT);

    public DataListInfoAOListener(IDataListInfoService dataListInfoService) {
        this.dataListInfoService = dataListInfoService;
    }

    /**
     * 这个每一条数据解析都会来调用
     * @param ao
     * @param analysisContext
     */
    @Override
    public void invoke(ImportDataListAO ao, AnalysisContext analysisContext) {
        cachedDataList.add(ao);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        log.info("{}条数据,开始存储数据库!", cachedDataList.size());
        dataListInfoService.saveImportDataListInfo(cachedDataList);
        log.info("存储数据库成功!");
    }
}

以上准备好后,写一下简单的controller就可以了

2.2.3 FileController

java 复制代码
	@PostMapping(value = "/import/data-resource-item")
    public CommonResult importDataResourceItem(@RequestPart("file") @NotEmpty(message = "文件不可为空") MultipartFile file) {
        if (file == null) {
            throw new BusinessException("文件不可为空");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xls") && !fileName.endsWith("xlsx")) {
            throw new BusinessException("不支持的文件格式");
        }
        return fileService.importDataResourceItem(file);
    }

//IFileService 
    CommonResult importDataResourceItem(MultipartFile file);
//FileServiceImpl
	@Override
    public CommonResult importDataResourceItem(MultipartFile file) {
        try {
            EasyExcel
                    .read(file.getInputStream(), ImportDataListAO.class,new DataListInfoAOListener(dataListInfoService))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.success();
    }

以上就是EasyExcel在SpringBoot项目中实现Excel文件导入数据入库的基本操作了,Say Bye!

相关推荐
【D'accumulation】17 分钟前
典型的MVC设计模式:使用JSP和JavaBean相结合的方式来动态生成网页内容典型的MVC设计模式
java·设计模式·mvc
试行32 分钟前
Android实现自定义下拉列表绑定数据
android·java
茜茜西西CeCe38 分钟前
移动技术开发:简单计算器界面
java·gitee·安卓·android-studio·移动技术开发·原生安卓开发
bjzhang7538 分钟前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
救救孩子把43 分钟前
Java基础之IO流
java·开发语言
flying jiang43 分钟前
Spring Boot 入门面试五道题
spring boot
小菜yh44 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
宇卿.1 小时前
Java键盘输入语句
java·开发语言
浅念同学1 小时前
算法.图论-并查集上
java·算法·图论
立志成为coding大牛的菜鸟.1 小时前
力扣1143-最长公共子序列(Java详细题解)
java·算法·leetcode