alibaba EasyExcel 导入 Excel 分享

前言:

Excel 导入是一个非常常见的功能,项目开发中随处可见,市面上也有各种处理 Excel 的 API,本文简单分享一下 alibaba.excel 的导入功能。

引入依赖:

xml 复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.1</version>
</dependency>

定义实体类:

java 复制代码
@Data
public class ImportVO {

    @ExcelProperty(index = 0, value = {"手机号"})
    private String phoneNo;

    @ExcelProperty(index = 1, value = {"用户姓名"})
    private String userName;

    @ApiModelProperty("分值")
    @ExcelProperty(index = 1, value = {"分值"})
    private BigDecimal score;

    @ApiModelProperty("部门")
    @ExcelProperty(index = 3, value = {"部门"})
    private String department;

}

创建监听器:

需要注意的是监听器不能被 Spring 管理,每次使用时需要 new 来创建对象,需要用到 Spring 对象的时候,可以通过构造方法传进去,或者使用 getBean 方法来获取。

java 复制代码
@Data
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class ImportListener extends AnalysisEventListener<SatisfactionEvaluationImportVO> {

	private AService aService;

    private BService bService;
	
	//构造方法 
    public ImportListener(AService aService, BService bService) {
        this.aService = aService;
        this.bService = bService;
    }

	//getBean
	private CService cService = SpringContextHolder.getBean("cServiceImpl");

    /**
     * 返回结果
     */
    private List<ImportVO> importDataList = new ArrayList<>();
  

    /**
     * @param headMap: key 表头索引 value 为名称
     * @param context:  
     * @author author
     * @date 2024/6/13 15:16
     * @description 表头校验
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        int count = 0;
        // 获取数据实体的字段列表
        Field[] fields = ImportVO.class.getDeclaredFields();
        // 遍历字段进行判断
        for (Field field : fields) {
            // 获取当前字段上的ExcelProperty注解信息
            ExcelProperty fieldAnnotation = field.getAnnotation(ExcelProperty.class);
            // 判断当前字段上是否存在ExcelProperty注解
            if (fieldAnnotation != null) {
                ++count;
                // 存在ExcelProperty注解则根据注解的index索引到表头中获取对应的表头名
                String headName = headMap.get(fieldAnnotation.index());
                // 判断表头是否为空或是否和当前字段设置的表头名不相同
                if (StringUtils.isEmpty(headName) || !headName.equals(fieldAnnotation.value()[0])) {
                    // 如果为空或不相同,则抛出异常不再往下执行
                    throw new RuntimeException("请使用正确的导入模板!");
                }
            }
        }

        // 判断用户导入表格的标题头是否完全符合模板
        if (count != headMap.size()) {
            throw new RuntimeException("请使用正确的导入模板!");
        }
    }

   
    /**
     * @param importVO: 
     * @param analysisContext:  
     * @author author
     * @date 2024/6/13 15:16
     * @description 每解析一行数据都会调用 invoke 方法
     */
    @Override
    public void invoke(ImportVO  importVO, AnalysisContext analysisContext) {
        int rowIndex = analysisContext.readRowHolder().getRowIndex() + 1;
        //数据校验--根据自己的业务需求

        //处理数据--根据自己的业务需求
   
        //加入结果集
        importDataList.add(importVO);
    }


     /**
     * @param analysisContext:  
     * @author author
     * @date 2024/6/13 15:19
     * @description 所有数据解析完了会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

Controller 层导入方法使用:

java 复制代码
@PostMapping("/import")
@ApiOperation(httpMethod = "POST", value = "导入测试", notes = "导入测试")
public RetVo<Void> satisfactionImport(@RequestParam("file") MultipartFile file) throws IOException {
	ImportSatisfactionEvaluationListener listener = new ImportSatisfactionEvaluationListener();
	try {
		//getbean 方式 获取bean
		EasyExcel.read(file.getInputStream(), ImportVO.class, new ImportListener()).sheet(0).headRowNumber(1).doRead();
		//构造方法获取 bean 
		EasyExcel.read(file.getInputStream(), ImportVO.class, ImportListener(aService, bService)).sheet(0).headRowNumber(1).doRead();
		List<ImportVO> excelDataList = listener.getImportDataList();
		if (CollectionUtils.isEmpty(excelDataList)) {
			throw new BizException("数据为空");
		}
		List<ImportDO>  satisfactionEvaluationList= BeanUtil.copyListProperties(excelDataList, ImportDO.class);
		//入库处理
	} catch (ExcelDataConvertException e) {
		throw new BizException(MessageFormat.format(UserInfoConstants.FORMAT_ERROR, (e.getRowIndex() + 1), (e.getColumnIndex() + 1)));
	}
	return RetVo.success();
}

总结:本文简单分享使用 alibaba EasyExcel 导入 Excel 的简单使用,只是简单的分享了主要流程及要点,具体的业务实现是根据业务来的,希望可以帮助到有需要的小伙伴。

欢迎提出建议及对错误的地方指出纠正。

相关推荐
砚底藏山河10 分钟前
【量化纯GET实战 #04】批量快照:一次 HTTP GET 取多只股票
java·python·金融·eclipse
君顾113 分钟前
家校托管互通:从需求分析到系统架构的落地实践
java·开发语言·托管
QQ_216962909618 分钟前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
xcl092535 分钟前
流浪宠物领养管理系统开发实战:从需求分析到落地的完整指南
java·spring boot·需求分析·宠物
lhldsg1 小时前
家校托管互通系统技术架构与实战设计
java·经验分享·小程序·架构
GIS数据转换器1 小时前
智慧林草“一张图“平台
java·大数据·服务器·前端·javascript·数据库·人工智能
gis开发之家1 小时前
Spring Boot 4 深度解析,JdbcTemplate 实战——轻量级数据库操作方案
java·数据库·spring boot·后端
mqiqe2 小时前
AgentScope Java 2.0 技能仓库(Skill Repository)完全实战指南
java·开发语言·elasticsearch
Mr数据杨2 小时前
【Codex】用学生支持周报模块跟踪个性化支持进展
android·java·javascript·django·codex·项目开发
JavaPub-rodert2 小时前
Apache Jena 详解:Java 开发者如何真正搭起一套知识图谱与语义服务
java·apache·知识图谱