spring boot导入导出excel,集成EasyExcel

news/2024/7/21 7:52:43 标签: spring boot, excel, java

一、安装依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.2.0</version>
        </dependency>

二、新建导出工具类

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.2.0</version>
        </dependency>

三、新建实体类

package com.example.springbootclickhouse.Excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.example.springbootclickhouse.ExcelValidTools.ExcelValid;
import com.example.springbootclickhouse.ExcelValidTools.NumberValid;
import com.example.springbootclickhouse.utils.GenderConverter;
import lombok.*;


import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentExcel implements Serializable {

    private static final long serialVersionUID = 1L;

    @ExcelProperty("姓名")
    @ColumnWidth(20)
    @ExcelValid(message = "姓名列不能有空数据!")
    private String name;

    @ExcelProperty("年龄")
    @ColumnWidth(20)
    @NumberValid(message = "年龄不得小于0")
    private Integer age;

    @ExcelProperty(value = "性别",converter = GenderConverter.class)
    @ColumnWidth(20)
    private Integer gender;

    @ExcelProperty("日期")
    @ColumnWidth(20)
    private LocalDateTime date;

}

@ExcelProperty: 核心注解,value属性可用来设置表头名称,converter属性可以用来设置类型转换器;

@ColumnWidth: 用于设置表格列的宽度;

@DateTimeFormat: 用于设置日期转换格式;

@NumberFormat: 用于设置数字转换格式。

四、如果需要有字段进行转换的,则为新建转换类,并在实体类上加注解
1、实体类上加如下

@ExcelProperty(value = "性别",converter = GenderConverter.class)

2、新建枚举类

package com.example.springbootclickhouse.ExcelEnum;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;

import java.util.stream.Stream;

@AllArgsConstructor
@Getter
public enum GenderEnum {
    /**
     * 未知
     */
    UNKNOWN(0, "未知"),

    /**
     * 男性
     */
    MALE(1, "男性"),

    /**
     * 女性
     */
    FEMALE(2, "女性");

    private final Integer value;

    @JsonFormat
    private final String description;

    public static GenderEnum convert(Integer value) {
//        用于为给定元素创建顺序流
//        values:获取枚举类型的对象数组
        return Stream.of(values())
                .filter(bean -> bean.value.equals(value))
                .findAny()
                .orElse(UNKNOWN);
    }

    public static GenderEnum convert(String description) {
        return Stream.of(values())
                .filter(bean -> bean.description.equals(description))
                .findAny()
                .orElse(UNKNOWN);
    }
}

3、新建转换器类

package com.example.springbootclickhouse.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;

import com.example.springbootclickhouse.ExcelEnum.GenderEnum;

public class GenderConverter implements Converter<Integer> {
    @Override
    public Class<?> supportJavaTypeKey() {
        // 实体类中对象属性类型
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        // Excel中对应的CellData(单元格数据)属性类型
        return CellDataTypeEnum.STRING;
    }

    /**
     * 将单元格里的数据转为java对象,也就是女转成2,男转成1,用于导入excel时对性别字段进行转换
     * */
    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) throws Exception {
        // 从CellData中读取数据,判断Excel中的值,将其转换为预期的数值
        return GenderEnum.convert(context.getReadCellData().getStringValue()).getValue();
    }
    /**
     * 将java对象转为单元格数据,也就是2转成女,1转成男,用于导出excel时对性别字段进行转换
     * */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) throws Exception {
        // 判断实体类中获取的值,转换为Excel预期的值,并封装为CellData对象
        return new WriteCellData<>(GenderEnum.convert(context.getValue()).getDescription());
    }
}

五、导入时,数据进行验证的话
1、新建注解

package com.example.springbootclickhouse.ExcelValidTools;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelValid {
    String message() default "导入有未填入的字段";
}

2、新建验证类

package com.example.springbootclickhouse.ExcelValidTools;

import java.lang.reflect.Field;
import java.util.Objects;

public class ExcelImportValid {
    /**
     * Excel导入字段校验
     * @param object 校验的JavaBean 其属性须有自定义注解
     */
    public static void valid(Object object,Integer rowIndex) throws Exception {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            //属性的值
            Object fieldValue = null;
            try {
                fieldValue = field.get(object);
            } catch (IllegalAccessException e) {
                throw new Exception("第" + rowIndex + "行" + field.getAnnotation(ExcelValid.class).message(),e);
            }
            //是否包含必填校验注解
            boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
            if (isExcelValid && Objects.isNull(fieldValue)) {
                throw new Exception("excel中第" + rowIndex + "行的" + field.getAnnotation(ExcelValid.class).message());
            }else if(isExcelValid && !(fieldValue instanceof Integer)){
                throw new Exception("excel中第" + rowIndex + "行的类型不正确" + field.getAnnotation(ExcelValid.class).message());
            }
        }
    }

    public static void validNumber(Object object,Integer rowIndex) throws Exception {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            //属性的值
            Object fieldValue = null;
            try {
                fieldValue = field.get(object);
            } catch (IllegalAccessException e) {
                throw new Exception("第" + rowIndex + "行" + field.getAnnotation(NumberValid.class).message(),e);
            }
            //是否包含必填校验注解
            boolean isExcelValid = field.isAnnotationPresent(NumberValid.class);
            if (isExcelValid && (Integer)fieldValue<=0) {
                throw new Exception("excel中第" + rowIndex + "行的" + field.getAnnotation(NumberValid.class).message());
            }
        }
    }
}

3、新建监听器类

package com.example.springbootclickhouse.ExcelValidTools;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.springbootclickhouse.Excel.StudentExcel;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.alibaba.druid.sql.dialect.mysql.ast.clause.MySqlFormatName.JSON;


@Slf4j
public class StudentListener extends AnalysisEventListener<StudentExcel> {
    private static final int BATCH_COUNT = 500;

    @Getter
    List<StudentExcel> list=new ArrayList<>(BATCH_COUNT);

    @Override
    @SneakyThrows
    public void invoke(StudentExcel studentExcel, AnalysisContext analysisContext) {

        log.info("数据校验:"+studentExcel);
        ExcelImportValid.valid(studentExcel,analysisContext.readRowHolder().getRowIndex()+1);
        ExcelImportValid.validNumber(studentExcel,analysisContext.readRowHolder().getRowIndex()+1);
        //可不用
//        list.add(studentExcel);
//        if (list.size() >= BATCH_COUNT) {
//            log.info("已经解析"+list.size()+"条数据");
//            list.clear();
//        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }




}

4、在实体类上使用注解@ExcelValid(message = “姓名列不能有空数据!”),同时在导入时新增

.registerReadListener(new StudentListener())

五、如果要求导出的excel加下拉选项框的话
1、新建导出处理类

package com.example.springbootclickhouse.ExcelHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CustomSheetWriteHandler implements SheetWriteHandler {
    /**
     * 想实现Excel引用其他sheet页数据作为单元格下拉选项值,
     * 需要重写该方法
     *
     * @param writeWorkbookHolder
     * @param writeSheetHolder
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 构造样例数据,该数据可根据实际需要,换成业务数据
        // 实际数据可通过构造方法,get、set方法等由外界传入
        List<String> selectDataList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            selectDataList.add("下拉选项" + i);
        }

        // 构造下拉选项单元格列的位置,以及下拉选项可选参数值的map集合
        // key:下拉选项要放到哪个单元格,比如A列的单元格那就是0,C列的单元格,那就是2
        // value:key对应的那个单元格下拉列表里的数据项,比如这里就是下拉选项1..100
        Map<Integer, List<String>> selectParamMap = new HashMap<>();
        selectParamMap.put(0, selectDataList);

        // 获取第一个sheet页
        Sheet sheet = writeSheetHolder.getCachedSheet();
        // 获取sheet页的数据校验对象
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 获取工作簿对象,用于创建存放下拉数据的字典sheet数据页
        Workbook workbook = writeWorkbookHolder.getWorkbook();

        // 迭代索引,用于存放下拉数据的字典sheet数据页命名
        int index = 1;
        for (Map.Entry<Integer, List<String>> entry : selectParamMap.entrySet()) {

            // 设置存放下拉数据的字典sheet,并把这些sheet隐藏掉,这样用户交互更友好
            String dictSheetName = "dict_hide_sheet" + index;
            Sheet dictSheet = workbook.createSheet(dictSheetName);
            // 隐藏字典sheet页
            workbook.setSheetHidden(index++, true);

            // 设置下拉列表覆盖的行数,从第一行开始到最后一行,这里注意,Excel行的
            // 索引是从0开始的,我这边第0行是标题行,第1行开始时数据化,可根据实
            // 际业务设置真正的数据开始行,如果要设置到最后一行,那么一定注意,
            // 最后一行的行索引是1048575,千万别写成1048576,不然会导致下拉列表
            // 失效,出不来
            CellRangeAddressList infoList = new CellRangeAddressList(1, 1048575, entry.getKey(), entry.getKey());
            int rowLen = entry.getValue().size();
            for (int i = 0; i < rowLen; i++) {
                // 向字典sheet写数据,从第一行开始写,此处可根据自己业务需要,自定
                // 义从第几行还是写,写的时候注意一下行索引是从0开始的即可
                dictSheet.createRow(i).createCell(0).setCellValue(entry.getValue().get(i));
            }

            // 设置关联数据公式,这个格式跟Excel设置有效性数据的表达式是一样的
            String refers = dictSheetName + "!$A$1:$A$" + entry.getValue().size();
            Name name = workbook.createName();
            name.setNameName(dictSheetName);
            // 将关联公式和sheet页做关联
            name.setRefersToFormula(refers);

            // 将上面设置好的下拉列表字典sheet页和目标sheet关联起来
            DataValidationConstraint constraint = helper.createFormulaListConstraint(dictSheetName);
            DataValidation dataValidation = helper.createValidation(constraint, infoList);
            sheet.addValidationData(dataValidation);
        }
    }
}

2、在导出代码注册

 EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(new CustomSheetWriteHandler())
                    .head(StudentExcel.class)
                    .sheet("sheet1")
                    .doWrite(userList);

http://www.niftyadmin.cn/n/5139811.html

相关文章

问题 C: 搬寝室(DP)

算法分析&#xff1a; 题目意思为求n个物品&#xff0c;拿k对使得消耗的体力最少&#xff0c; 或者说是这k对物品&#xff0c;每一对中两件物品的质量差平方最小&#xff0c; 所以要使得质量差的平方小&#xff0c;只能排序后取质量相邻两个物品作为一对&#xff1b; 现在设f…

游戏在小米设备上因自适应刷新率功能,帧率减半

1&#xff09;游戏在小米设备上因自适应刷新率功能&#xff0c;帧率减半 2&#xff09;Lua在计算时出现非法值&#xff0c;开启Debugger之后不再触发 3&#xff09;如何在Unity中实现液体蔓延的效果 这是第357篇UWA技术知识分享的推送&#xff0c;精选了UWA社区的热门话题&…

Linux系统中的SWAP、Cache和Buffer详解

在Linux系统中&#xff0c;内存管理是至关重要的一环。为了提高系统性能和效率&#xff0c;Linux采用了多种技术来管理和优化内存的使用。其中&#xff0c;SWAP&#xff08;虚拟内存交换区&#xff09;、Cache&#xff08;缓存区&#xff09;和Buffer&#xff08;输入输出缓存区…

西门子精智触摸屏使用U盘下载程序时报错“出现严重错误,必须关机”处理办法

西门子精智触摸屏使用U盘下载程序时报错“出现严重错误,必须关机”处理办法 如下图所示,精智触摸屏使用U盘下载程序时报错: Application CTLPNL. EXE encountered a serious error and must shut down 出现这种情况时,可以尝试从以下几方面进行逐个排查: 断电重启,更换U盘…

无人机队形控制的算法

无人机队形控制的算法通常有以下几种&#xff1a; 1&#xff0e;长机-僚机法&#xff08;Leader-Follower&#xff09;&#xff1a;该算法通过设定一架无人机作为长机&#xff0c;其他无人机作为僚机&#xff0c;通过长机的信息来控制僚机的运动&#xff0c;以达到队形控制的目…

P2359 三素数数 , 线性dp

题目背景 蛟川书院的一道练习题QAQ 题目描述 如果一个数的所有连续三位数字都是大于100的素数&#xff0c;则该数称为三素数数。比如113797是一个6位的三素数数。 输入格式 一个整数n&#xff08;3 ≤ n ≤ 10000&#xff09;&#xff0c;表示三素数数的位数。 输出格式 …

Android开发知识学习——Kotlin进阶

文章目录 次级构造主构造器init 代码块构造属性data class相等性解构Elvis 操作符when 操作符operatorLambdainfix 函数嵌套函数注解使用处目标函数简化函数参数默认值扩展函数类型内联函数部分禁用用内联具体化的类型参数抽象属性委托属性委托类委托 Kotlin 标准函数课后题 次…

Android WMS——DisplayContent介绍(十一)

前面整体介绍了 WMS 中 addWindow 方法整体调用流程,其中首先就是从 mRoot(RootWindowContainer)中获取 DisplayContent ,如果没有就会根据 displayId 创建一个新的 DisplayContent。这里我们主要看一下 DisplayContent 的相关功能。 一、简介 在 Android 的 WMS(Window …