🧠 一、為什么用 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
📁 導出功能在企業系統中非常常見,如果你在寫后臺管理系統,這篇教程絕對值得收藏!