🧠 一、为什么用 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
📁 导出功能在企业系统中非常常见,如果你在写后台管理系统,这篇教程绝对值得收藏!