Spring Boot整合Easy Excel

Spring Boot整合Easy Excel

什么是Easy Excel?

EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。

他能让你在不用考虑性能、内存的等因素的情况下,快速完成Excel的读、写等功能。

Spring Boot 整合 Easy Excel

添加依赖

xml 复制代码
<dependency>
	<!-- 根据最新版本进行修改 -->
    <dependency>
    	<groupId>com.alibaba</groupId>
	    <artifactId>easyexcel</artifactId>
        <version>3.3.2</version>
    </dependency>
        <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel-core</artifactId>
        <version>3.3.2</version>
    </dependency>
</dependency>

读取excel

java 复制代码
public static List<ExcelData> readExcel(String url, int sheetNo) {
        List<ExcelData> dataList = new ArrayList<>(); // 存储读取的Excel数据列表

        // Excel 文件路径
        String excelFilePath = url;

        // 使用 EasyExcel 读取 Excel 文件,并指定要读取的 sheet
        EasyExcel.read(excelFilePath, ExcelData.class, new ExcelDataListener(dataList))
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetNo - 1) // sheet 索引从0开始,所以需要减1
                .doRead();

        return dataList;
    }

写入excel

java 复制代码
public static void writeToExcel(List<?> dataList, String filePath, String sheetName, Class<?> clazz) {
        ExcelWriter excelWriter = null;
        try {
            // 创建 ExcelWriter 对象,并指定 Excel 文件路径
            excelWriter = EasyExcel.write(filePath, clazz).build();

            // 创建 WriteSheet 对象,并指定 Excel 工作表名称
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();

            // 将数据写入 Excel 文件
            excelWriter.write(dataList, writeSheet);
        } finally {
            // 关闭 ExcelWriter 对象,释放资源
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

参考文献

官方文档

相关推荐
朦胧之1 小时前
PostgreSQL 数据库笔记
人工智能·后端
user_admin_god2 小时前
数据采集/交换系统设计经验
spring boot·spring·策略模式
IT_陈寒4 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
LucianaiB4 小时前
用 WorkBuddy 研究腾讯、阿里和 DeepSeek,我没敢直接说「AI 很赚钱」
后端
用户8356290780514 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
分支预测失败4 小时前
RISC-V 上下文切换实战:从 Trap 入口到 Linux 进程调度
后端·嵌入式
学代码的CJY5 小时前
Linux 重定向、管道与环境变量
linux·spring boot·spring
用户8356290780515 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
Profile排查笔记5 小时前
JavaScript 实现浏览器指纹生成:基础字段、Canvas 采样与 SHA-256 摘要
前端·人工智能·后端·自动化
GoGeekBaird5 小时前
我给 DeepSeek Harness 造了个铸造台
后端