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实体属性的对应方式,并支持一些特殊操作(如自动填充,逻辑删除等)。

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

    常用属性
    属性 类型 说明 示例
    value String[] Excel列名(支持多级表头) @ExcelProperty("姓名")
    index int 列索引(从0开始) @ExcelProperty(index = 0)
    converter Class 自定义数据转换器 @ExcelProperty(converter = CustomConverter.class)
    format String 日期/数字格式 @ExcelProperty(format = "yyyy-MM-dd")
    ignore boolean 是否忽略该字段 @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);
    }
}

Logo

全面兼容主流 AI 模型,支持本地及云端双模式

更多推荐