Spring Boot 实现 Excel 导出功能(支持前端下载 + 文件流)

🧠 一、为什么用 EasyExcel?

在 Java 开发中,操作 Excel 的框架主要有:

  • Apache POI(经典但慢、内存占用大)

  • JXL(老旧不维护)

  • Alibaba EasyExcel(阿里出品,性能好,写入快,注解灵活)

EasyExcel 优点:

  • 注解式开发,简单直观

  • 支持大量数据写入不 OOM

  • 支持复杂表头、样式、合并单元格

今天我们用 EasyExcel 实现后端导出 Excel 文件并支持前端下载。


📦 二、添加依赖(Maven)

复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.2</version>
</dependency>

🧱 三、定义导出数据结构

创建一个导出用的数据对象(VO),使用 @ExcelProperty 注解指定表头名和字段顺序:

复制代码
package com.example.excel.vo;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class UserExportVO {

    @ExcelProperty(value = "用户名", index = 0)
    private String username;

    @ExcelProperty(value = "手机号", index = 1)
    private String phone;

    @ExcelProperty(value = "注册时间", index = 2)
    private String registerTime;
}

🖥️ 四、后端导出接口

创建一个下载接口,核心是将 Excel 写入 HttpServletResponse 输出流。

复制代码
@GetMapping("/api/export")
public void exportUserList(HttpServletResponse response) throws IOException {
    List<UserExportVO> dataList = getMockData(); // 获取数据(或从数据库查询)

    // 设置响应头
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");

    String fileName = URLEncoder.encode("用户信息导出", "UTF-8").replaceAll("\\+", "%20");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

    // 写数据到响应输出流
    EasyExcel.write(response.getOutputStream(), UserExportVO.class)
            .sheet("用户信息")
            .doWrite(dataList);
}

✅ 示例 mock 数据方法

复制代码
private List<UserExportVO> getMockData() {
    List<UserExportVO> list = new ArrayList<>();
    for (int i = 1; i <= 10; i++) {
        UserExportVO user = new UserExportVO();
        user.setUsername("用户" + i);
        user.setPhone("188888888" + i);
        user.setRegisterTime("2025-04-10");
        list.add(user);
    }
    return list;
}

🌐 五、前端调用方式

方式一:直接触发下载(window.open)

复制代码
window.open('/api/export', '_blank');

方式二:使用 Axios 下载 Blob

复制代码
axios({
  url: '/api/export',
  method: 'GET',
  responseType: 'blob'
}).then((res) => {
  const blob = new Blob([res.data], { type: res.headers['content-type'] });
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = '用户信息.xlsx';
  link.click();
});

🧩 六、常见问题解答

❓1. 文件名乱码?

✅ 使用 URLEncoder.encode(fileName, "UTF-8") 编码,并加 replaceAll("\\+", "%20")

❓2. 表头顺序错乱?

✅ 使用 @ExcelProperty(index = x) 指定每列的顺序。

❓3. 导出文件打不开?

✅ 确保响应头设置正确,文件类型为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

❓4. 导出大量数据内存溢出?

✅ EasyExcel 默认使用 streaming write,但建议分页获取数据、分批写入。


📌 七、结语

到这里,我们已经完成了:

✅ 使用 EasyExcel 构建导出数据结构

✅ 实现了后端文件流输出接口

✅ 支持前端触发导出并自动下载 Excel

📁 导出功能在企业系统中非常常见,如果你在写后台管理系统,这篇教程绝对值得收藏!

相关推荐
圣光SG7 分钟前
Excel 函数大全
算法·excel
fengxinzi_zack17 分钟前
年统计与最长连续天数:数据聚合可视化
后端
全堆鸿蒙19 分钟前
aboutToAppear 生命周期:路由参数获取与数据初始化
后端
2501_9318037524 分钟前
Go 反射:原理、核心机制与实践指南
开发语言·后端·golang
程序员爱钓鱼36 分钟前
Rust if let 与 while let 详解:简化模式匹配
前端·后端·rust
我是唐青枫44 分钟前
Java Neo4j 实战指南:从图模型、Cypher 到 Spring Boot 关系查询
java·spring boot·neo4j
爸爸6191 小时前
UIAbility 生命周期在日记 App 中的实践
后端·华为·harmonyos·鸿蒙系统
大阳光男孩10 小时前
Spring Boot 整合 Debezium 实现 MySQL 增量数据监听(嵌入式版)
spring boot·后端·mysql
皮皮林55110 小时前
ThreadLocal 不香了?ScopedValue才是王道?
后端
X-⃢_⃢-X11 小时前
一、第一阶段:认识 Spring Boot
java·spring boot·后端