easy Exsel导出

目录

一、首先引入依赖

二、然后封装一个VO

三、Controller层

四、Service实现类 

引用样式

自适应列宽  

自适应行高

五、测试

postman

​编辑

 浏览器

异常


分配到这个任务了,写个小demo记录下,具体可参考EasyExcel官方文档

我用的是web上传、下载那块代码

一、首先引入依赖

        <!--    easy Excel    --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.0</version><exclusions><exclusion><artifactId>poi-ooxml-schemas</artifactId><groupId>org.apache.poi</groupId></exclusion></exclusions></dependency>

二、然后封装一个VO

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class ExportStudentInfoVO implements Serializable {private static final long serialVersionUID = -3275970951989418695L;@ExcelIgnore // 忽略导出private String stuId;@ExcelProperty("学生姓名")private String stuName;@ExcelProperty("学生性别")private String stuGender;@ExcelProperty("学生年龄")private Integer stuAge;@ExcelProperty("监护人联系方式")private String guardianPhone;@DateTimeFormat("yyyy-MM-dd HH:mm:ss")@ColumnWidth(21) //设置宽度@ExcelProperty(value = "入学时间")private Date createDate;
}

三、Controller层

@RestController
@RequestMapping("info")
public class InfoController {@Resourceprivate InfoService infoService;@Operation(summary = "学生信息导出")@RequestMapping(value = "/excelDownload", method = RequestMethod.GET, produces = "application/json; charset=utf-8")public void excelOrderContainerDownload(HttpServletResponse response){infoService.excelDownload(response);}}

四、Service实现类 

这里的list,模拟从DB中查到的数据

.registerWriteHandler(new CustomCellWriteWidthConfig()) /*自适应列宽*/
 .registerWriteHandler(new CustomCellWriteHeightConfig()) /*自适应行高*/
.registerWriteHandler(EasyExcelUtils.getStyleStrategy()) /*引用样式*/

以上三个是excel表格进行一个处理,让其看起来更加美观,如果要使用可以往下翻对应的代码复制使用,不加也不影响导出

@Service
@Slf4j
public class InfoServiceImpl  implements InfoService {@Overridepublic void excelDownload(HttpServletResponse response) {List<ExportStudentInfoVO> list = new ArrayList<>();list.add(new ExportStudentInfoVO("001","张三","男",18,"18488789989", new Date()));list.add(new ExportStudentInfoVO("002","李四","女",21,"15233337777", new Date()));list.add(new ExportStudentInfoVO("003","王五","男",19,"15623332333", new Date()));try {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");String currentDate = sdf.format(new Date());// URLEncoder.encode 可以防止中文乱码String fileName = URLEncoder.encode("学生信息列表" + currentDate, "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");EasyExcel.write(response.getOutputStream(), ExportStudentInfoVO.class).sheet("学生信息").registerWriteHandler(new CustomCellWriteWidthConfig()) /*自适应列宽*/.registerWriteHandler(new CustomCellWriteHeightConfig()) /*自适应行高*/.registerWriteHandler(EasyExcelUtils.getStyleStrategy()) /*引用样式*/.doWrite(list);} catch (Exception e) {log.error("导出失败~");e.printStackTrace();}}}

引用样式

package cn.homed.common.utils.excel;import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;public class EasyExcelUtils {/*** 设置excel样式*/public static HorizontalCellStyleStrategy getStyleStrategy() {// 头的策略  样式调整WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 头背景 浅绿headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());WriteFont headWriteFont = new WriteFont();// 头字号headWriteFont.setFontHeightInPoints((short) 12);// 字体样式headWriteFont.setFontName("宋体");headWriteCellStyle.setWriteFont(headWriteFont);// 自动换行headWriteCellStyle.setWrapped(true);// 设置细边框headWriteCellStyle.setBorderBottom(BorderStyle.THIN);headWriteCellStyle.setBorderLeft(BorderStyle.THIN);headWriteCellStyle.setBorderRight(BorderStyle.THIN);headWriteCellStyle.setBorderTop(BorderStyle.THIN);// 设置边框颜色 25灰度headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 水平对齐方式headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);// 垂直对齐方式headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 内容的策略 宋体WriteCellStyle contentStyle = new WriteCellStyle();// 设置垂直居中contentStyle.setWrapped(true);contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置 水平居中
//        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);WriteFont contentWriteFont = new WriteFont();// 内容字号contentWriteFont.setFontHeightInPoints((short) 12);// 字体样式contentWriteFont.setFontName("宋体");contentStyle.setWriteFont(contentWriteFont);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现return new HorizontalCellStyleStrategy(headWriteCellStyle, contentStyle);}
}

自适应列宽  

package cn.homed.common.utils.excel;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;import java.util.HashMap;
import java.util.List;
import java.util.Map;public class CustomCellWriteWidthConfig extends AbstractColumnWidthStyleStrategy {private final Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = CACHE.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>());Integer columnWidth = this.dataLength(cellDataList, cell, isHead);// 单元格文本长度大于60换行if (columnWidth >= 0) {if (columnWidth > 60) {columnWidth = 60;}Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);Sheet sheet = writeSheetHolder.getSheet();sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);}}}}/*** 计算长度* @param cellDataList* @param cell* @param isHead* @return*/private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData<?> cellData = cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch (type) {case STRING:// 换行符(数据需要提前解析好)int index = cellData.getStringValue().indexOf("\n");return index != -1 ?cellData.getStringValue().substring(0, index).getBytes().length + 1 : cellData.getStringValue().getBytes().length + 1;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}
}

自适应行高

package cn.homed.common.utils.excel;import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;import java.util.Iterator;public class CustomCellWriteHeightConfig extends AbstractRowHeightStyleStrategy {/*** 默认高度*/private static final Integer DEFAULT_HEIGHT = 300;@Overrideprotected void setHeadColumnHeight(Row row, int relativeRowIndex) {}@Overrideprotected void setContentColumnHeight(Row row, int relativeRowIndex) {Iterator<Cell> cellIterator = row.cellIterator();if (!cellIterator.hasNext()) {return;}// 默认为 1行高度int maxHeight = 1;while (cellIterator.hasNext()) {Cell cell = cellIterator.next();if (cell.getCellTypeEnum() == CellType.STRING) {String value = cell.getStringCellValue();int len = value.length();int num = 0;if (len > 50) {num = len % 50 > 0 ? len / 50 : len / 2 - 1;}if (num > 0) {for (int i = 0; i < num; i++) {value = value.substring(0, (i + 1) * 50 + i) + "\n" + value.substring((i + 1) * 50 + i, len + i);}}if (value.contains("\n")) {int length = value.split("\n").length;maxHeight = Math.max(maxHeight, length) + 1;}}}row.setHeight((short) ((maxHeight) * DEFAULT_HEIGHT));}
}

五、测试

测试的话可以用postman进行测试 ,或者把链接粘在浏览器上

postman

postman测试的时候记得点这个下拉框选择发送并下载

然后弹出这个界面点击保存

然后桌面上就可以看到已经成功的下载下来了,数据也都是没问题的

 浏览器

直接贴链接即可

可以看到数据也是没问题的 

异常

最后讲一下,刚开始我这个小demo没跑起来,编译、运行都没问题,一调接口就报错了

异常是 com.alibaba.excel.exception.ExcelGenerateException: java.lang.NoClassDefFoundError: org/apache/xmlbeans/impl/common/SystemCache

搜了一下是由于缺少了相关的依赖库或者版本不匹配所致,可能需要添加 Apache POI 或者 XMLBeans 这些依赖库,并且确保版本号是兼容的。

然后加上这两个依赖就可以了,不知道你们有没有遇到

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>

好了,分享就到这里,晚安

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

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

相关文章

CCC数字钥匙设计【NFC基础】--LPCD相关介绍

关于NFC卡检测&#xff0c;主要可以分成两个步骤&#xff1a; 1、LPCD低功耗检测&#xff0c;唤醒NFC读卡器。 2、唤醒后&#xff0c;NFC读卡器或MCU控制器轮询Type A、Type B、Type F、Type V&#xff08;ISO15693&#xff09;等卡类型。 本文主要介绍LPCD相关功能&#xff…

设备管理——WinCC 给你神助功

要实现“设备高效”&#xff0c;就必须“管之有道”&#xff0c;来自设备层的数据支撑将是必不可少的&#xff0c;提高设备效能的2个关键在于降低平时停机时间 (MDT) 和提高平均无故障时间 (MTBF)。通常来说&#xff0c;设备维护可大致可分为三个层次&#xff1a;纠正性维护&am…

c++ mysql数据库编程(linux系统)

ubuntu下mysql数据库的安装 ubuntu安装mysql&#xff08;图文详解&#xff09;-CSDN博客https://blog.csdn.net/qq_58158950/article/details/135667062?spm1001.2014.3001.5501 项目目录结构 数据库及表结构 public.h //打印错误信息 #ifndef PUBLIC_h #define PUBLIC_H…

【详解】通讯录项目

目录 通讯录项目要求&#xff1a; 引言&#xff1a; 步骤如下&#xff1a; 用户的数据类型&#xff1a; 初始化循序表&#xff1a; 菜单&#xff1a; 添加联系人&#xff1a; 删除联系人&#xff1a; 修改联系人&#xff1a; 查找联系人&#xff1a; 查看通讯录&…

《WebKit 技术内幕》之七(1): 渲染基础

《WebKit 技术内幕》之七&#xff08;1&#xff09;&#xff1a; 渲染基础 WebKit的布局计算使用 RenderObject 树并保存计算结果到 RenderObject 树。 RenderObject 树同其他树&#xff08;如 RenderLayer 树等&#xff09;&#xff0c;构成了 WebKit 渲染的为要基础设施。 1…

【RT-DETR有效改进】Google | EfficientNetV1一种超轻量又高效的网络 (附代码 + 添加教程)

前言 大家好&#xff0c;我是Snu77&#xff0c;这里是RT-DETR有效涨点专栏。 本专栏的内容为根据ultralytics版本的RT-DETR进行改进&#xff0c;内容持续更新&#xff0c;每周更新文章数量3-10篇。 专栏以ResNet18、ResNet50为基础修改版本&#xff0c;同时修改内容也支持Re…

python算法与数据结构---排序和归并排序

学习目标 掌握归并排序的基本原理使用python语言解答归并排序题目 归并排序 原理及过程 将两个有序的数组合并成一个有序数组称为从上往下分解&#xff1a;把当前区间一分为二&#xff0c;直至分解为若干个长度为1的子数组从上往下的合并&#xff1a;两个有序的子区域两两向…

Pytest 测试框架与Allure 测试报告——Allure2测试报告-L1

目录&#xff1a; allure2安装 Allure2介绍Allure2报告展示Allure2报告展示-首页概览Allure2报告展示-用例详情页Allure2安装Allure2下载与安装Allure环境验证插件安装-Python插件安装-Java验证插件安装-Javaallure2运行方式 生成测试报告流程使用Allure2运行方式-Python使用A…

FaFu--练习复盘--3

4、指针的应用 4.1、三角形周长和面积计算程序 描述 已知三角形的三条边的长度&#xff0c;求该三角形的周长和面积&#xff0c;如果三个边不能构成三角形&#xff0c;则三角形的周长和面积都为0。完成程序的编写。 输入 输入1行&#xff0c;包含3个实数&#xff0c;各实数之…

大模型关键技术:上下文学习、思维链、RLHF、参数微调、并行训练、旋转位置编码、模型加速、大模型注意力机制优化、永久记忆、LangChain、知识图谱、多模态

大模型关键技术 大模型综述上下文学习思维链 CoT奖励建模参数微调并行训练模型加速永久记忆&#xff1a;大模型遗忘LangChain知识图谱多模态大模型系统优化AI 绘图幻觉问题从 GPT1 - GPT4 拆解GPTs 对比主流大模型技术点旋转位置编码层归一化激活函数注意力机制优化 大模型综述…

四种方法将 Docker Registry 迁移至 Harbor

Registry Docker Distribution Docker Distribution 是第一个是实现了打包、发布、存储和镜像分发的工具&#xff0c;起到 docker registry 的作用。&#xff08;目前 Distribution 已经捐赠给了 CNCF&#xff09;。其中 Docker Distribution 中的 spec 规范后来也就成为了 O…

在线WebOffce在HTML/VUE/Electron纯前端网页编辑Office之打开Word后自动处于修订模式

在线办公协同办公过程中&#xff0c;对于老板给出的文档修改&#xff0c;如果在错别字方面都要自己一个个字去看的话也太浪费时间了&#xff0c;其实word上就有一个修订模式&#xff0c;可以帮助大家高效完成文档的修改&#xff0c;在线WebOffce在HTML/VUE/Electron纯前端网页编…

Semaphone应用源码分析

Semaphone应用&源码分析 3.1 Semaphore介绍 sync&#xff0c;ReentrantLock是互斥锁&#xff0c;保证一个资源同一时间只允许被一个线程访问 Semaphore&#xff08;信号量&#xff09;保证1个或多个资源可以被指定数量的线程同时访问 底层实现是基于AQS去做的。 Semap…

pinia 的使用方法

使用方式&#xff08;选项式&#xff09; 1、在 mian.js 导入 pinia 里的 createPinia 函数。 2、app.use 这个 createPinia 函数的返回值。 // main.jsimport { createPinia } from pinia;app.use(createPinia()); 3、创建一个 js 文件&#xff08;该文件保存着共享的数据&…

Git和SVN

1、Git Git是一个分布式版本控制系统&#xff0c;由Linus Torvalds创建&#xff0c;用于有效、高速地处理从小到大的项目版本管理。Git是开源的&#xff0c;采取了分布式的版本库的方式&#xff0c;不需要服务器端软件就可以运行。 Git的核心概念 以下是Git中的一些核心概念…

《Python数据分析技术栈》第03章 02 数据结构(Structure of data)

02 数据结构&#xff08;Structure of data&#xff09; 《Python数据分析技术栈》第03章 02 数据结构&#xff08;Structure of data&#xff09; The data that we need to analyze could have any of the following structures, 我们需要分析的数据可能具有以下任何一种结…

RabbitMQ-数据持久化

一、持久化类型 1、交换机持久化&#xff08;SpringAMQP默认&#xff09; 2、队列持久化&#xff08;SpringAMQP默认&#xff09; 3、消息持久化 二、消息持久化 1、纯内存操作 如果采用纯内存操作&#xff0c;那么消息存储达到队列的上限之后&#xff0c;会有一个page ou…

开源进程/任务管理服务Meproc使用之HTTP API

本文讲述如何使用开源进程/任务管理服务Meproc的HTTP API管理整个服务。 Meproc所提供的全部 API 的 URL 都是相同的。 http://ip:port/proc例如 http://127.0.0.1:8606/proc在下面的小节中&#xff0c;我们使用curl命令向您展示 API 的方法、参数和请求正文。 启动任务 …

git 常规操作及设置

git 常规操作及设置 Git是一个分布式版本控制系统&#xff0c;可以用来跟踪文件的修改历史并与其他人进行协作开发。下面是一些常见的Git操作及设置&#xff1a; 初始化仓库&#xff1a;使用命令git init在当前目录创建一个新的Git仓库。 克隆仓库&#xff1a;使用命令git clo…

TCP/IP协议及配置、IP地址、子网掩码、网关地址、DNS与DHCP介绍

一、什么是服务器 能够为其他计算机提供服务的更高级的电脑 尺寸:Unit 1u1.75英寸44.45mm4.445cm IDC&#xff08;机房&#xff09; C/S结构 Client/Server客户端和服务端 二、TCP/IP协议 计算机与计算机之间通信的协议 三要素&#xff1a; IP地址 子网掩码 IP路由 I…