Java复杂表头的Excel导入功能实现

 更新时间:2025年09月22日 09:27:21   作者:键盘侠Gu  
本篇文章主要介绍如何使用Java相关的技术,来实现复杂表头的excel导入功能,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

1、概述

在实现Java中的excel导入功能是,有时会遇到复杂的表头结构,即表头由多行或者多列组成,并且包含合并单元格等复杂的布局。本篇文章主要介绍如何使用Java相关的技术,来实现复杂表头的excel导入功能。

2、实现步骤

  • 提前准备好Excel模板文件和相关的pom文件依赖库;
  • 解析表头,并创建与表头相同的实体类;
  • 编写监听器,监听Excel实体类相关注解,进行解析;
  • 使用EasyExcel进行文件导入

3、代码实现

首先创建一个与表头想呼应的实体类,例如

对应实体类如下,

package com.guyk.web.domain.dto;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
 * @ClassName:ProtectionZoneExcel
 * @Author: guyk
 * @Date: 2025/2/26 14:14
 * @Description:
 */
@Data
public class ProtectionZoneExcel {
    private static final long serialVersionUID = 1L;
    @ExcelProperty(value = {"序号", "序号", "序号", "序号"}, index = 0)
    private String id;
    @ApiModelProperty("河流名称")
    @TableField("river_name")
    @ExcelProperty(value = {"河流", "河流名称", "河流名称", "河流名称"}, index = 1)
    private String riverName;
    @ApiModelProperty("河流编码")
    @TableField("river_code")
    @ExcelProperty(value = {"河流", "河流编码", "河流编码", "河流编码"}, index = 2)
    private String riverCode;
    @ApiModelProperty("保护区名称")
    @TableField("protected_area_name")
    @ExcelProperty(value = {"防洪保护区信息", "保护区名称", "保护区名称", "保护区名称"}, index = 3)
    private String protectedAreaName;
    @ApiModelProperty("防护类型")
    @TableField("protection_type")
    @ExcelProperty(value = {"防洪保护区信息", "防护类型", "防护类型", "防护类型"}, index = 4)
    private String protectionType;
    @ApiModelProperty("面积(平方千米)")
    @TableField("square_measure")
    @ExcelProperty(value = {"防洪保护区信息", "面积(km²)", "面积(km²)", "面积(km²)"}, index = 5)
    private String squareMeasure;
    @ApiModelProperty("地图坐标-经度")
    @TableField("map_lng")
    @ExcelProperty(value = {"防洪保护区信息", "地图坐标", "东经", "东经"}, index = 6)
    private String mapLng;
    @ApiModelProperty("地图坐标-纬度")
    @TableField("map_lat")
    @ExcelProperty(value = {"防洪保护区信息", "地图坐标", "北纬", "北纬"}, index = 7)
    private String mapLat;
    @ApiModelProperty("现状防洪标准")
    @TableField("current_flood_control_standards")
    @ExcelProperty(value = {"防洪保护区信息", "防洪标准", "现状", "现状"}, index = 8)
    private String currentFloodControlStandards;
    @ApiModelProperty("设计防洪标准")
    @TableField("design_flood_control_standards")
    @ExcelProperty(value = {"防洪保护区信息", "防洪标准", "设计", "设计"}, index = 9)
    private String designFloodControlStandards;
    @ApiModelProperty("城镇-名称")
    @TableField("town_name")
    @ExcelProperty(value = {"保护对象", "城镇", "名称", "名称"}, index = 10)
    private String townName;
    @ApiModelProperty("城镇-常住人口(万人)")
    @TableField("town_permanent_population")
    @ExcelProperty(value = {"保护对象", "城镇", "常住人口(万人)", "常住人口(万人)"}, index = 11)
    private String townPermanentPopulation;
    @ApiModelProperty("城镇-GDP(亿元)")
    @TableField("town_gdp")
    @ExcelProperty(value = {"保护对象", "城镇", "GDP(亿元)", "GDP(亿元)"}, index = 12)
    private String townGdp;
    @ApiModelProperty("城镇-经度")
    @TableField("town_lng")
    @ExcelProperty(value = {"保护对象", "城镇", "坐标", "东经"}, index = 13)
    private String townLng;
    @ApiModelProperty("城镇-纬度")
    @TableField("town_lat")
    @ExcelProperty(value = {"保护对象", "城镇", "坐标", "北纬"}, index = 14)
    private String townLat;
    @ApiModelProperty("乡村-名称")
    @TableField("countryside_name")
    @ExcelProperty(value = {"保护对象", "乡村", "名称", "名称"}, index = 15)
    private String countrysideName;
    @ApiModelProperty("乡村-常住人口(万人)")
    @TableField("countryside_permanent_population")
    @ExcelProperty(value = {"保护对象", "乡村", "常住人口(万人)", "常住人口(万人)"}, index = 16)
    private String countrysidePermanentPopulation;
    @ApiModelProperty("乡村-经度")
    @TableField("countryside_lng")
    @ExcelProperty(value = {"保护对象", "乡村", "坐标", "东经"}, index = 17)
    private String countrysideLng;
    @ApiModelProperty("乡村-纬度")
    @TableField("countryside_lat")
    @ExcelProperty(value = {"保护对象", "乡村", "坐标", "北纬"}, index = 18)
    private String countrysideLat;
    @ApiModelProperty("耕地-面积(万亩)")
    @TableField("cropland_square_measure")
    @ExcelProperty(value = {"保护对象", "耕地", "面积(万亩)", "面积(万亩)"}, index = 19)
    private String croplandSquareMeasure;
    @ApiModelProperty("耕地-基本农田(万亩)")
    @TableField("cropland_basic_farmland")
    @ExcelProperty(value = {"保护对象", "耕地", "其中:基本农田(万亩)", "其中:基本农田(万亩)"}, index = 20)
    private String croplandBasicFarmland;
    @ApiModelProperty("耕地-经度")
    @TableField("cropland_lng")
    @ExcelProperty(value = {"保护对象", "耕地", "坐标", "东经"}, index = 21)
    private String croplandLng;
    @ApiModelProperty("耕地-纬度")
    @TableField("cropland_lat")
    @ExcelProperty(value = {"保护对象", "耕地", "坐标", "北纬"}, index = 22)
    private String croplandLat;
    @ApiModelProperty("重要基础设施-名称")
    @TableField("critical_infrastructure_name")
    @ExcelProperty(value = {"保护对象", "重要基础设施", "名称", "名称"}, index = 23)
    private String criticalInfrastructureName;
    @ApiModelProperty("重要基础设施-防护等级")
    @TableField("critical_infrastructure_protection_grade")
    @ExcelProperty(value = {"保护对象", "重要基础设施", "防护等级", "防护等级"}, index = 24)
    private String criticalInfrastructureProtectionGrade;
    @ApiModelProperty("重要基础设施-经度")
    @TableField("critical_infrastructure_lng")
    @ExcelProperty(value = {"保护对象", "重要基础设施", "坐标", "东经"}, index = 25)
    private String criticalInfrastructureLng;
    @ApiModelProperty("重要基础设施-纬度")
    @TableField("critical_infrastructure_lat")
    @ExcelProperty(value = {"保护对象", "重要基础设施", "坐标", "北纬"}, index = 26)
    private String criticalInfrastructureLat;
    @ExcelProperty(value = {"备注", "备注", "备注", "备注"}, index = 27)
    private String remark;
}

其中,实体类中的注解及其含义如下

  • @ApiModelProperty注解:swagger注解。为API木星的属性提供额外的描述信息,为了生成更清晰的接口文档。常用属性如下
    常用属性
    属性说明示例
    value字段描述@ApiModelProperty(value = "用户ID")
    example示例值@ApiModelProperty(example = "123")
    required是否必填@ApiModelProperty(required = true)
    hidden隐藏字段@ApiModelProperty(hidden = true)
    dataType数据类型(可选)@ApiModelProperty(dataType = "java.lang.Integer")
  • @TableField注解:mybatis-plus注解。用于标注实体类(Entity)的字段与数据库表的列之间的映射关系。它提供了更灵活的数据库字段与Java实体属性的对应方式,并支持一些特殊操作(如自动填充,逻辑删除等)。

    常用属性
    属性类型说明示例
    valueString数据库字段名(默认按驼峰转下划线)@TableField("user_name")
    existboolean是否对应数据库字段(默认true,若false表示非数据库字段)@TableField(exist = false)
    fillFieldFill自动填充策略(如插入/更新时填充)@TableField(fill = FieldFill.INSERT)
    selectboolean查询时是否包含该字段(默认true)@TableField(select = false)
    conditionStringWHERE条件预处理(较少用)@TableField(condition = "%s=#{%s}")
  • @ExcelProperty注解:EasyExcel框架中的注解,用于定义Java对象属性与Excel表格列之间的映射关系,主要用于Excel的导入和导出。

    常用属性
    属性类型说明示例
    valueString[]Excel列名(支持多级表头)@ExcelProperty("姓名")
    indexint列索引(从0开始)@ExcelProperty(index = 0)
    converterClass自定义数据转换器@ExcelProperty(converter = CustomConverter.class)
    formatString日期/数字格式@ExcelProperty(format = "yyyy-MM-dd")
    ignoreboolean是否忽略该字段@ExcelProperty(ignore = true)

监听器

package com.guyk.web.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.guyk.web.domain.dto.ProtectionZoneExcel;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * @ClassName:ProtectionZoneImportExcelListener
 * @Author: guyk
 * @Date: 2025/2/26 14:37
 * @Description:
 */
public class ProtectionZoneImportExcelListener extends AnalysisEventListener<ProtectionZoneExcel> {
    private List<ProtectionZoneExcel> list = new ArrayList<>();
    private List<ProtectionZoneExcel> filteredList = new ArrayList<>();
    @Override
    public void invoke(ProtectionZoneExcel protectionZoneExcel, AnalysisContext analysisContext) {
        list.add(protectionZoneExcel);
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        filteredList = list.stream().filter(protectionZoneExcel -> Objects.nonNull(protectionZoneExcel.getId())).filter(protectionZoneExcel -> protectionZoneExcel.getId().matches("\\d+")).collect(Collectors.toList());
    }
    public List<ProtectionZoneExcel> getFilteredList() {
        return filteredList;
    }
    public List<ProtectionZoneExcel> getList() {
        return list;
    }
}

上传接口

@ApiOperation("导入保护区Excel")
@PostMapping("/protectionZoneImport")
public R<Boolean> protectionZoneImport(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    InputStream inputStream = null;
    try {
        inputStream = file.getInputStream();
        ProtectionZoneImportExcelListener listener = new ProtectionZoneImportExcelListener();
        EasyExcel.read(inputStream, ProtectionZoneExcel.class, listener).sheet().doRead();
        // 导入之后,入库
        log.info("解析成功!准备处理!");
        return R.ok(this.protectionZoneService.protectionZoneImport(listener));
    } catch (IOException e) {
        log.info("入库失败!", e);
        return R.fail(Boolean.FALSE);
    }
}

到此这篇关于Java复杂表头的Excel导入的文章就介绍到这了,更多相关java excel导入复杂表头内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • mybatis Invalid bound statement(not found)排坑记录

    mybatis Invalid bound statement(not foun

    这篇文章主要介绍了mybatis Invalid bound statement(not found)排坑记录,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • IDEA中程序包Org.Springframework.Boot不存在问题及解决

    IDEA中程序包Org.Springframework.Boot不存在问题及解决

    这篇文章主要介绍了IDEA中程序包Org.Springframework.Boot不存在问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Spring boot2X Consul如何通过RestTemplate实现服务调用

    Spring boot2X Consul如何通过RestTemplate实现服务调用

    这篇文章主要介绍了spring boot2X Consul如何通过RestTemplate实现服务调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • ClassLoader双亲委派模式作用详解

    ClassLoader双亲委派模式作用详解

    这篇文章主要为大家介绍了ClassLoader双亲委派模式作用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • 任何Bean通过实现ProxyableBeanAccessor接口即可获得动态灵活的获取代理对象或原生对象的能力(最新推荐)

    任何Bean通过实现ProxyableBeanAccessor接口即可获得动态灵活的获取代理对象或原生对象的能力(最新推

    这篇文章主要介绍了任何Bean通过实现ProxyableBeanAccessor接口即可获得动态灵活的获取代理对象或原生对象的能力,通过示例代码看到,借助ProxyableBeanAccessor接口默认实现的getReal、getProxy、selfAs方法,很灵活的按需获取代理或非代理对象,需要的朋友可以参考下
    2024-02-02
  • 前端WebSocket连接失败问题的排查过程及解决

    前端WebSocket连接失败问题的排查过程及解决

    WebSocket是一种全双工通信协议,它允许通过单个长久的TCP连接在客户端和服务器之间进行实时双向通信,这篇文章主要介绍了前端WebSocket连接失败问题的排查过程及解决办法,需要的朋友可以参考下
    2025-07-07
  • Spring Boot如何整合FreeMarker模板引擎

    Spring Boot如何整合FreeMarker模板引擎

    这篇文章主要介绍了Spring Boot如何整合FreeMarker模板引擎,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • Java源码分析:Guava之不可变集合ImmutableMap的源码分析

    Java源码分析:Guava之不可变集合ImmutableMap的源码分析

    今天给大家带来的是关于Java源码的相关知识,文章围绕着Java ImmutableMap展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下,希望能给你带来帮助
    2021-06-06
  • Mybatis打印SQL语句的几种常用方式

    Mybatis打印SQL语句的几种常用方式

    当我们动态sql拼接的块很多的时候,我们要想从*mapper.xml中直接找出完整的sql就会非常的难,这个时候经常会需要把组合之后的完整SQL语句打印出来,对调试非常有帮助的,所以本文小编给大家介绍了几种Mybatis打印SQL语句的常用方式,需要的朋友可以参考下
    2023-11-11
  • Java常用的Arrays函数举例详解

    Java常用的Arrays函数举例详解

    这篇文章主要给大家介绍了关于Java常用Arrays函数举例详解的相关资料,Java数组常用方法包括sort、toString、equals、fill、copyOf等,涵盖数组排序、比较、填充与拷贝,需要的朋友可以参考下
    2025-05-05

最新评论