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

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

相关推荐
Oneslide11 分钟前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp13 分钟前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒1 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569152 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆3 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L3 小时前
LangGraph入门学习资料
后端
神奇小汤圆4 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
后端
kfaino4 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
lwx572804 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
云技纵横5 小时前
Spring Boot Actuator 被打穿:线上开了这些端点,等于裸奔
后端