当前位置: 首页 > news >正文

spring boot导入导出excel,集成EasyExcel

一、安装依赖

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

二、新建导出工具类

package com.example.springbootclickhouse.utils;import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;public class ExcelReponseTools {//设置导出样式public static void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");String fileName = URLEncoder.encode(rawFileName, "UTF-8");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");}
}

三、新建实体类

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;@JsonFormatprivate 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> {@Overridepublic Class<?> supportJavaTypeKey() {// 实体类中对象属性类型return Integer.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {// Excel中对应的CellData(单元格数据)属性类型return CellDataTypeEnum.STRING;}/*** 将单元格里的数据转为java对象,也就是女转成2,男转成1,用于导入excel时对性别字段进行转换* */@Overridepublic Integer convertToJavaData(ReadConverterContext<?> context) throws Exception {// 从CellData中读取数据,判断Excel中的值,将其转换为预期的数值return GenderEnum.convert(context.getReadCellData().getStringValue()).getValue();}/*** 将java对象转为单元格数据,也就是2转成女,1转成男,用于导出excel时对性别字段进行转换* */@Overridepublic 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 org.apache.commons.lang3.StringUtils;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());}}}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 && (Objects.isNull(fieldValue) || StringUtils.isBlank(fieldValue.toString()))) {throw new Exception("excel中第" + rowIndex + "行的年龄不得为空");}else if(isExcelValid && !(fieldValue instanceof Integer)){throw new Exception("excel中第" + rowIndex + "行的年龄必须为正整数");}else 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.util.ArrayList;
import java.util.List;
import java.util.Map;@Slf4j
public class StudentListener extends AnalysisEventListener<StudentExcel> {private static final int BATCH_COUNT = 500;@GetterList<StudentExcel> list=new ArrayList<>(BATCH_COUNT);@Override@SneakyThrowspublic 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();
//        }}/*** 每解析一行表头,会调用该方法** @param headMap* @param context*/@Overridepublic void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {if (!headMap.containsKey(0) || !headMap.containsKey(1) || !headMap.containsKey(2) || !headMap.containsKey(3)|| !headMap.get(0).equals("姓名") || !headMap.get(1).equals("年龄")|| !headMap.get(2).equals("性别") || !headMap.get(3).equals("日期")) {throw new RuntimeException("表头校验失败");}}@Overridepublic 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*/@Overridepublic 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..100Map<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);

七、根据条件单元格样式调整
1、新建处理器类

package com.example.springbootclickhouse.ExcelHandler;import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.*;public class CustomCellWriteHandler implements CellWriteHandler {/*** 生成的Excel表格的第9列*/private static final Integer COLUMN_INDEX = 1;/*** 有效期的区间数字_60*/private static final Integer NUMBER_60 = 60;/*** 有效期的区间数字_30*/private static final Integer NUMBER_30 = 30;/*** 有效期的区间数字_0*/private static final Integer NUMBER_0 = 0;@Overridepublic void afterCellDispose(CellWriteHandlerContext context) {if (BooleanUtils.isNotTrue(context.getHead())) {Cell cell = context.getCell();Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式// 不同单元格尽量传同一个 cellStyleCellStyle cellStyle = workbook.createCellStyle();if (cell.getColumnIndex() == COLUMN_INDEX ) {Double doubleCellValue = (Double) cell.getNumericCellValue();Integer count = doubleCellValue.intValue();//下方设置字体颜色Font writeFont = workbook.createFont();if (count > NUMBER_60){writeFont.setColor(IndexedColors.GREEN.getIndex());}else if (count >= NUMBER_30){writeFont.setColor(IndexedColors.YELLOW.getIndex());}else if (count >= NUMBER_0){writeFont.setColor(IndexedColors.RED.getIndex());}else {writeFont.setColor(IndexedColors.GREY_25_PERCENT.getIndex());}cellStyle.setFont(writeFont);//                //设置单元格颜色
//                if (count > NUMBER_60){
//                    cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
//                }else if (count >= NUMBER_30){
//                    cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
//                }else if (count >= NUMBER_0){
//                    cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
//                }//                cellStyle.setBorderLeft(BorderStyle.MEDIUM);
//                cellStyle.setBorderRight(BorderStyle.MEDIUM);
//                cellStyle.setBorderBottom(BorderStyle.THIN);
//                cellStyle.setBorderTop(BorderStyle.THIN);// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
//                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellStyle);// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到// cell里面去 会导致自己设置的不一样context.getFirstCellData().setWriteCellStyle(null);}}}
}

2、在导出时注册一下

ExcelReponseTools.setExcelResponseProp(response, "用户列表");List<StudentExcel> userList = this.prepareData();EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).head(StudentExcel.class).sheet("sheet1").doWrite(userList);

八、表头样式
1、修改表头字体颜色,在实体类上新增如下注解

@HeadStyle(fillForegroundColor = 50)@HeadFontStyle(color = 9,bold = BooleanEnum.FALSE)

fillForegroundColor 对应的颜色值如下图:

在这里插入图片描述

相关文章:

  • CMake引用OSG
  • react使用react-sortable-hoc实现拖拽
  • 海外媒体发稿:如何利用8种出口贸易媒体发稿实现销售突破-华媒舍
  • 路由器基础(七):NAT原理与配置
  • 数据中心系统解决方案
  • XXL-JOB 默认 accessToken 身份绕过导致 RCE
  • 计算机视觉基础——基于yolov5-face算法的车牌检测
  • dubbo集群容错策略
  • mediasoup webrtc音视频会议搭建
  • 【KVM】软件虚拟化和硬件虚拟化类型
  • JavaScript执行上下文和调用栈
  • chrome 扩展 popup 弹窗的使用
  • 微信小程序 uCharts的使用方法
  • (自适应手机端)响应式新闻博客知识类pbootcms网站模板 自媒体运营博客网站源码下载
  • Session+Cookie实现登录认证
  • 2017-09-12 前端日报
  • const let
  • Git的一些常用操作
  • JAVA_NIO系列——Channel和Buffer详解
  • JavaScript类型识别
  • JavaScript学习总结——原型
  • Java的Interrupt与线程中断
  • java正则表式的使用
  • php中curl和soap方式请求服务超时问题
  • python大佬养成计划----difflib模块
  • select2 取值 遍历 设置默认值
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • text-decoration与color属性
  • windows-nginx-https-本地配置
  • 人脸识别最新开发经验demo
  • 深度学习在携程攻略社区的应用
  • 使用API自动生成工具优化前端工作流
  • 硬币翻转问题,区间操作
  • 由插件封装引出的一丢丢思考
  • ​Spring Boot 分片上传文件
  • ​你们这样子,耽误我的工作进度怎么办?
  • # C++之functional库用法整理
  • #我与Java虚拟机的故事#连载02:“小蓝”陪伴的日日夜夜
  • (Python第六天)文件处理
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (官网安装) 基于CentOS 7安装MangoDB和MangoDB Shell
  • (排序详解之 堆排序)
  • (十六)串口UART
  • (十五)devops持续集成开发——jenkins流水线构建策略配置及触发器的使用
  • (四)模仿学习-完成后台管理页面查询
  • (提供数据集下载)基于大语言模型LangChain与ChatGLM3-6B本地知识库调优:数据集优化、参数调整、Prompt提示词优化实战
  • (一)Neo4j下载安装以及初次使用
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • ./configure,make,make install的作用(转)
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .net core使用ef 6
  • .net mvc 获取url中controller和action
  • [ JavaScript ] JSON方法
  • [] 与 [[]], -gt 与 > 的比较
  • []常用AT命令解释()