EasyExcel--导入和导出Excel的方法

原文网址:EasyExcel--导入和导出Excel的方法_IT利刃出鞘的博客-CSDN博客

简介

本文介绍SpringBoot整合EasyExcel导入和导出Excel的方法。

使用

Excel导入

实体类

@Data
public class OrderImportBO {@ExcelProperty("订单号")@NotBlank(message = "订单号不能为空")private String scOrderPoolId;@ExcelProperty("金额")private String amount;
}

Controller

@PostMapping("importOrder")
public void importOrder(@RequestPart MultipartFile file) {List<OrderImportBO> orderImportBOList = ExcelUtil.importExcel(file, OrderImportBO.class);
}

Excel导出

 实体类

@Data
public class OrderExportBO {@ExcelProperty("订单号")@NotBlank(message = "订单号不能为空")private String scOrderPoolId;@ExcelProperty("金额")private String amount;
}

Service

List<OrderExportVO> exportVOS = new ArrayList();
ExcelUtil.exportExcel(exportVOS, OrderExportVO.class);

详细代码

依赖

EasyExcel

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

整个pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.knife</groupId><artifactId>demo_EasyExcel_SpringBoot</artifactId><version>0.0.1-SNAPSHOT</version><name>demo_EasyExcel_SpringBoot</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.11</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version><scope>provided</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.0.RELEASE</version></plugin></plugins></build></project>

Excel配置

字符串转换器

package com.knife.excel.handler;import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;public class StringConverter implements Converter<String> {@Overridepublic Class supportJavaTypeKey() {return String.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}/*** 将excel对象转成Java对象,这里读的时候会调用*/@Overridepublic String convertToJavaData(CellData cellData, 
ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return cellData.getStringValue().trim();}/*** 将Java对象转成String对象,写出的时候调用*/@Overridepublic CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return new CellData(value);}
}

writeHandler

package com.knife.excel.halper;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;import java.util.HashMap;
import java.util.List;
import java.util.Map;public class ExcelHandler extends AbstractColumnWidthStyleStrategy {private static final int MAX_COLUMN_WIDTH = 255;//因为在自动列宽的过程中,有些设置地方让列宽显得紧凑,所以做出了个判断private static final int COLUMN_WIDTH = 20;private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);public ExcelHandler() {}@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap(16);CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(cellDataList, cell, isHead);if (columnWidth >= 0) {if (columnWidth > MAX_COLUMN_WIDTH) {columnWidth = MAX_COLUMN_WIDTH;}else {if(columnWidth<COLUMN_WIDTH){columnWidth =columnWidth*2;}}Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(),  columnWidth* 256);}}}}private  Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = (CellData)cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch(type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}public static HorizontalCellStyleStrategy getStyleStrategy(){// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 背景设置为灰色headWriteCellStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());WriteFont headWriteFont = new WriteFont();headWriteFont.setFontHeightInPoints((short)11);// 字体样式headWriteFont.setFontName("Arial Unicode MS");headWriteFont.setColor(IndexedColors.WHITE.getIndex());headWriteCellStyle.setWriteFont(headWriteFont);//自动换行headWriteCellStyle.setWrapped(false);// 水平对齐方式headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);// 垂直对齐方式headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 内容的策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定// contentWriteCellStyle.setFillPatternType(FillPatternType.SQUARES);// 背景白色contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());WriteFont contentWriteFont = new WriteFont();// 字体大小contentWriteFont.setFontHeightInPoints((short)11);// 字体样式contentWriteFont.setFontName("宋体");contentWriteCellStyle.setWriteFont(contentWriteFont);//是否换行contentWriteCellStyle.setWrapped(false);//  垂直对齐方式contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);}
}

数据校验

package com.bondex.oms.excel;import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.knife.util.BeanHelper;
import com.knife.util.ValidateUtil;public class ExcelValidateListener<T> extends AnalysisEventListener<T> {@Overridepublic void invoke(T bo, AnalysisContext analysisContext) {// 如果是空行,不处理if (BeanHelper.allFieldAreNull(bo)) {return;}int row = analysisContext.readRowHolder().getRowIndex() + 1;try {// 校验输入字段ValidateUtil.validate(bo);} catch (Exception e) {throw new RuntimeException("第[" + row + "]行数据校验失败:" + e.getMessage());}}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {}
}

 Bean工具

package com.knife.util;import org.springframework.beans.BeanUtils;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.CollectionUtils;import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;public class BeanHelper {public static <T> List<T> convert(List<?> sources, Class<T> target) {if (CollectionUtils.isEmpty(sources)) {return new ArrayList<>();}List<T> targets = new LinkedList<>();for (Object source : sources) {T t = null;try {t = target.newInstance();} catch (Exception e) {throw new RuntimeException(e);}BeanUtils.copyProperties(source, t);targets.add(t);}return targets;}public static <T> T convert(Object source, Class<T> target) {if (source == null) {return null;}T t;try {t = target.newInstance();} catch (Exception e) {throw new RuntimeException(e);}BeanUtils.copyProperties(source, t);return t;}public static boolean allFieldAreNull(Object o) {Class<?> aClass = o.getClass();PropertyDescriptor[] beanProperties = ReflectUtils.getBeanProperties(aClass);for (PropertyDescriptor beanProperty : beanProperties) {Method readMethod = beanProperty.getReadMethod();try {Object value = readMethod.invoke(o);if (value != null) {return false;}} catch (IllegalAccessException | InvocationTargetException e) {throw new RuntimeException(e);}}return true;}
}

Excel工具类

package com.bondex.oms.util;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.knife.entity.UserDTO;
import com.knife.util.UserDtoUtils;
import com.knife.excel.helper.ExcelHandler;
import com.knife.excel.helper.ExcelValidateListener;
import com.knife.excel.helper.HeadRowListener;
import com.knife.excel.helper.StringConverter;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;public class ExcelUtil {public static <T> void exportExcel(List<T> dataList,Class<T> tClass) {ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();Assert.notNull(servletRequestAttributes, "RequestAttributes不能为null");HttpServletResponse response = servletRequestAttributes.getResponse();Assert.notNull(response, "Response不能为null");ServletOutputStream out = null;try {out = response.getOutputStream();} catch (IOException e) {throw new RuntimeException(e);}String fileName = "测试文件.xlsx";try {// 必须要转一下,否则中文文件名会乱码fileName = URLEncoder.encode(fileName, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}// 通知浏览器以附件的形式下载处理,设置返回头要注意文件名有中文response.setHeader("Content-disposition", "attachment;filename=" + fileName);response.setContentType("multipart/form-data");response.setCharacterEncoding("utf-8");// 输出流到浏览器下载EasyExcel.write(out).needHead(true).head(tClass).excelType(ExcelTypeEnum.XLSX).autoCloseStream(true).registerWriteHandler(new ExcelHandler()).registerWriteHandler(ExcelHandler.getStyleStrategy()).sheet(0, "Sheet1").doWrite(dataList);}public static <T> List<T> importExcel(MultipartFile file, Class<T> tClass) {return importExcel(file, tClass, 1, null);}public static <T> List<T> importExcel(MultipartFile file, Class<T> tClass, String sheet) {return importExcel(file, tClass, 1, sheet);}public static <T> List<T> importExcel(MultipartFile file,Class<T> tClass,Integer headRowNumber,String sheet) {InputStream inputStream;try {inputStream = file.getInputStream();} catch (IOException e) {throw new RuntimeException(e);}List<T> list = null;list = EasyExcel.read(inputStream).registerConverter(new StringConverter()).registerReadListener(new ExcelValidateListener<T>()).head(tClass)// 可以指定sheet名字,不指定或null则表示第1个.sheet(sheet).headRowNumber(headRowNumber).doReadSync();list.removeIf(BeanHelper::allFieldAreNull);return list;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/35179.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

浏览器好用的去广告插件和暗黑模式护眼插件

提升浏览体验&#xff1a;Edge浏览器的Adblock和Dark Mode扩展 Adblock&#xff1a;告别广告干扰 功能&#xff1a;高效拦截弹窗、横幅和视频广告&#xff0c;提升网页整洁度&#xff0c;加快加载速度&#xff0c;节省流量。安装链接&#xff1a;安装Adblock Dark Mode for E…

MySQL-基础篇

从数据库的基础的概念特性到数据库当中的SQL语句&#xff0c;再到数据库当中的存储引擎、索引优化以及分库分表、数据库的集群&#xff0c;甚至于数据库的底层原理 MySQL概述SQL函数约束多表查询事务 这块由于上学期学过一些就速过。 MySQL概述 通过SQL就可以操作数据库管理…

fastapi+angular外卖系统

说明&#xff1a; fastapiangular外卖系统 1.美食分类&#xff08;粥&#xff0c;粉&#xff0c;面&#xff0c;炸鸡&#xff0c;炒菜&#xff0c;西餐&#xff0c;奶茶等等&#xff09; 2.商家列表 &#xff08;kfc&#xff0c;兰州拉面&#xff0c;湘菜馆&#xff0c;早餐店…

2025高频面试算法总结篇【递归回溯动态规划】

文章目录 递归&回溯131. 分割回文串面试题 08.12. 八皇后 动态规划72编辑距离5. 最长回文子串279. 完全平方数300. 最长递增子序列139. 单词拆分 递归&回溯 131. 分割回文串 回溯思路&#xff1a; 临界条件&#xff1a; if (start s.length) > 保存 循环遍历这个…

Ubuntu docker安装milvusdb

一、安装docker 1.更新软件包 sudo apt update sudo apt upgrade sudo apt-get install docker-ce docker-ce-cli containerd.io查看是否安装成功 docker -v二、使用国内的镜像下载 milvusdb Docker中国区官方镜像: https://registry.docker-cn.com milvusdb/milvus - Doc…

Redis如何实现持久化

Redis如何实现持久化 Redis默认将所有数据存储在内存中&#xff0c;虽然读写效率极高&#xff0c;但存在两大风险 数据易失性&#xff1a;进程重启或服务器宕机导致内存数据丢失。恢复成本高&#xff1a;无法直接通过内存重建大规模数据集。 Redis作为高性能的键值数据库&…

DeepSeek进阶应用(二):结合Kimi制作PPT(双AI协作教程)

&#x1f31f;引言&#xff1a; DeepSeek作为国产AI大模型&#xff0c;以强大的逻辑推理和结构化内容生成能力著称&#xff0c;擅长根据用户需求生成PPT大纲或Markdown文本&#xff1b;Kimi的PPT助手则能解析结构化内容并套用模板快速生成美观的PPT&#xff0c;两者结合实现“内…

查看分析日志文件、root密码不记得了,那应该怎么解决这些问题

下面我来讲解一下概念以及应该怎么做&#xff1a; 查看分析日志文件 一、主要日志文件 ♣ 内核及系统日志&#xff1a;这种日志数据由系统服务rsyslog统一管理&#xff0c;根据其主配置文件 /etc/rsyslog.conf 中的设置决定将内核消息及各种系统程序信息记录到什么位置。系统中…

mac电脑如何将wps接入deepseek (傻瓜式教学)

我的是mac pro m4 pro版本,版本不同页面或许有些许差异 首先将wps更新到最新的版本,并打开,点击 + 号 新建一个word文档 点击空白文档 点击开发工具,如果没有开发工具,可以先点击工具,在里面找到开发工具,然后点击宏安全性,设置为低,如下图所示

SpringMVC(五)拦截器

目录 拦截器基本概念 一 单个拦截器的执行 1 创建拦截器 2 SpringMVC配置&#xff0c;并指定拦截路径。 3 运行结果展示&#xff1a; 二 多个拦截器的执行顺序 三 拦截器与过滤器的区别 拦截器基本概念 SpringMVC内置拦截器机制&#xff0c;允许在请求被目标方法处理的…

3.17[A]CV

在计算机图形学中&#xff0c;反走样&#xff08;Antialiasing&#xff09; 是一种用于减少图像中锯齿状边缘&#xff08;aliasing artifacts&#xff09;的技术。当绘制曲线或图形时&#xff0c;由于像素的离散性&#xff0c;曲线边缘可能会出现锯齿状的失真。反走样通过考虑曲…

集成学习(上):Bagging集成方法

一、什么是集成学习&#xff1f; 在机器学习的世界里&#xff0c;没有哪个模型是完美无缺的。就像古希腊神话中的"盲人摸象"&#xff0c;单个模型往往只能捕捉到数据特征的某个侧面。但当我们把多个模型的智慧集合起来&#xff0c;就能像拼图一样还原出完整的真相&a…

【LangChain】理论及应用实战(5):Agent

文章目录 一、基本介绍1.1 Agent介绍1.2 Agent示例 二、几种主要的Agent类型2.1 ZERO_SHOT_REACT_DESCRIPTION2.2 CHAT_ZERO_SHOT_REACT_DESCRIPTION2.3 CONVERSATIONAL_REACT_DESCRIPTION2.4 CHAT_CONVERSATIONAL_REACT_DESCRIPTION2.5 OPENAI_FUNCTIONS 三、给Agent增加Memor…

口袋书签系统:AI 智能生成分类描述,省时又高效

口袋书签一键触达&#xff0c;免费使用&#xff1a;https://navfinder.cn/ 口袋书签系统新增了“根据收藏站点&#xff0c;AI自动生成分类描述”的功能&#xff0c;简要说明如下&#xff1a; 自动分析站点信息 系统会根据用户当前分类中的站点标题、标签等信息&#xff0c;结合…

AtCoder Beginner Contest 397 A - D题解

Tasks - OMRON Corporation Programming Contest 2025 (AtCoder Beginner Contest 397) 本文为 AtCoder Beginner Contest 397 A - D题解 题目A: 代码(C): #include <bits/stdc.h>int main() {double n;std::cin >> n;if (n > 38.0) {std::cout << 1;}…

linux按照nginx

第一步先按照依赖gcc 一键安装上面四个依赖 Nginx的编译安装需要一些依赖库&#xff0c;如gcc、make、zlib、openssl等。可以使用yum命令安装这些依赖&#xff1a; yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel 创建目录 mkdir /usr/nginx 切换…

Muon: An optimizer for hidden layers in neural networks

引言 在深度学习领域&#xff0c;优化算法对模型训练效率和性能起着关键作用。从经典的随机梯度下降 (SGD) 及其动量法&#xff0c;到自适应优化方法 Adam/AdamW 等&#xff0c;一系列优化器大大加速了神经网络的收敛。然而&#xff0c;随着模型规模和数据量的爆炸式增长&…

数据结构与算法-图论-拓扑排序

前置芝士 概念 拓扑排序&#xff08;Topological Sorting&#xff09;是对有向无环图&#xff08;DAG&#xff0c;Directed Acyclic Graph&#xff09;的顶点进行排序的一种算法。它将图中的所有顶点排成一个线性序列&#xff0c;使得对于图中的任意一条有向边 (u, v)&#x…

市长海报/ Mayor‘s posters

AB 省 Bytetown 的市民无法忍受市长竞选活动的候选人随心所欲地将他们的选举海报贴在各个地方。市议会最终决定建造一面选举墙来放置海报&#xff0c;并引入以下规则&#xff1a; 每个候选人都可以在墙上放置一张海报。所有海报的高度都与墙壁的高度相同;海报的宽度可以是任意整…

LeetCode hot 100—验证二叉搜索树

题目 给你一个二叉树的根节点 root &#xff0c;判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下&#xff1a; 节点的左子树只包含 小于 当前节点的数。节点的右子树只包含 大于 当前节点的数。所有左子树和右子树自身必须也是二叉搜索树。 示例 示例 1&#…