SpringBoot中的文件下載功能實(shí)現(xiàn)教程
一、文件下載的兩種實(shí)現(xiàn)方式
在Spring Boot應(yīng)用中,文件下載主要有兩種實(shí)現(xiàn)方式:
直接流式下載:
- 將文件內(nèi)容直接寫(xiě)入HTTP響應(yīng)流
- 不保存到服務(wù)器磁盤(pán)
- 適合小文件或即時(shí)生成的內(nèi)容
靜態(tài)資源映射下載:
- 先將文件保存到服務(wù)器
- 通過(guò)靜態(tài)資源映射提供訪問(wèn)
- 適合大文件或需要重復(fù)下載的場(chǎng)景
二、直接流式下載實(shí)現(xiàn)
核心代碼實(shí)現(xiàn):
// ExcelXlsUtil.java
public static void writeXls(HttpServletResponse response,
String fileName,
String[] headers,
List<List<String>> data) throws IOException {
// 1. 創(chuàng)建工作簿和工作表
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
// 2. 創(chuàng)建表頭行
HSSFRow headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headers[i]);
}
// 3. 填充數(shù)據(jù)行
for (int i = 0; i < data.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
List<String> rowData = data.get(i);
for (int j = 0; j < rowData.size(); j++) {
row.createCell(j).setCellValue(rowData.get(j));
}
}
// 4. 設(shè)置響應(yīng)頭
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
// 5. 寫(xiě)入響應(yīng)流
try (OutputStream os = response.getOutputStream()) {
workbook.write(os);
}
workbook.close();
}控制器調(diào)用示例
@GetMapping("/downloadDirect")
public void downloadDirect(HttpServletResponse response) throws IOException {
// 1. 準(zhǔn)備數(shù)據(jù)
String[] headers = {"ID", "姓名", "手機(jī)號(hào)"};
List<List<String>> data = Arrays.asList(
Arrays.asList("1", "張三", "13800138000"),
Arrays.asList("2", "李四", "13900139000")
);
// 2. 調(diào)用下載工具
ExcelXlsUtil.writeXls(response, "用戶(hù)列表", headers, data);
}三、靜態(tài)資源映射下載實(shí)現(xiàn)
這里我通過(guò)了一個(gè)分頁(yè)查詢(xún)的函數(shù)將某一頁(yè)的數(shù)據(jù)查詢(xún)出來(lái)了
@GetMapping("/exportExcel")
public Result exportAndSaveExcel(PersonSelectForm personSelectForm) throws IOException {
// 1. 獲取數(shù)據(jù)
List<PersonForm> resultList = getresList(personSelectForm);
// 2. 創(chuàng)建工作簿和工作表
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
// 3. 寫(xiě)入數(shù)據(jù)
int rowIndex = 0;
// 3.1 寫(xiě)標(biāo)題(合并單元格)
HSSFRow titleRow = sheet.createRow(rowIndex++);
titleRow.createCell(0).setCellValue("住戶(hù)信息明細(xì)表");
// 合并第一行單元格(0行,合并0~8列)
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
// 3.2 寫(xiě)表頭
HSSFRow headerRow = sheet.createRow(rowIndex++);
String[] headers = new String[] {
"ID", "小區(qū)名稱(chēng)", "所屬樓棟", "房號(hào)", "姓名", "性別", "手機(jī)號(hào)碼", "居住性質(zhì)", "備注"
};
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headers[i]);
}
// 3.3 寫(xiě)數(shù)據(jù)行
for (PersonForm person : resultList) {
HSSFRow row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(person.getPersonId() != null ? person.getPersonId().toString() : "");
row.createCell(1).setCellValue(person.getCommunityName() != null ? person.getCommunityName() : "");
row.createCell(2).setCellValue(person.getTermName() != null ? person.getTermName() : "");
row.createCell(3).setCellValue(person.getHouseNo() != null ? person.getHouseNo() : "");
row.createCell(4).setCellValue(person.getUserName() != null ? person.getUserName() : "");
row.createCell(5).setCellValue(person.getSex() != null ? person.getSex() : "");
row.createCell(6).setCellValue(person.getMobile() != null ? person.getMobile() : "");
row.createCell(7).setCellValue(person.getPersonType() != null ? person.getPersonType() : "");
row.createCell(8).setCellValue(person.getRemark() != null ? person.getRemark() : "");
}
// 4. 生成文件名
String fileName = "住戶(hù)信息_" + System.currentTimeMillis() + ".xls";
// 5. 定義保存路徑,確保路徑最后有分隔符
String excelpath = "D:\\javacode\\community_vue\\community\\FileXls\\";
File dir = new File(excelpath);
if (!dir.exists()) {
dir.mkdirs();
}
// 6. 完整文件路徑
File file = new File(excelpath + fileName);
// 7. 寫(xiě)入本地文件
try (FileOutputStream fos = new FileOutputStream(file)) {
workbook.write(fos);
} finally {
workbook.close();
}
// 8. 返回相對(duì)路徑或文件名(前端用下載接口訪問(wèn),不建議直接返回本地絕對(duì)路徑)
String relativePath = fileName; // 你可以根據(jù)自己配置修改
// 如果你沒(méi)有配置靜態(tài)資源映射,需要寫(xiě)一個(gè)下載接口來(lái)讀取 D:\javacode\community_vue\community\FileXls 文件夾里的文件
return Result.ok().put("data", relativePath);
}四、實(shí)現(xiàn)流程

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot+TCP監(jiān)聽(tīng)服務(wù)器搭建過(guò)程圖解
這篇文章主要介紹了Springboot+TCP監(jiān)聽(tīng)服務(wù)器搭建過(guò)程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
SpringBoot簡(jiǎn)單整合ElasticSearch實(shí)踐
Elasticsearch支持結(jié)構(gòu)化和非結(jié)構(gòu)化數(shù)據(jù)檢索,通過(guò)索引創(chuàng)建和倒排索引文檔,提高搜索效率,它基于Lucene封裝,分為索引庫(kù)、類(lèi)型、文檔和字段,Spring Boot可方便操作ES,通過(guò)依賴(lài)配置、實(shí)體類(lèi)映射和ElasticsearchRepository接口實(shí)現(xiàn)CRUD操作2025-12-12
Java多線程之同步工具類(lèi)CyclicBarrier
這篇文章主要介紹Java多線程之同步工具類(lèi)CyclicBarrier,它是一個(gè)同步工具類(lèi),它允許一組線程互相等待,直到達(dá)到某個(gè)公共屏障點(diǎn),支持一個(gè)可選的Runnable命令,在一組線程中的最后一個(gè)線程到達(dá)之后,該命令只在每個(gè)屏障點(diǎn)運(yùn)行一次。下面來(lái)看文章具體內(nèi)容2021-10-10
java中List<對(duì)象>如何根據(jù)對(duì)象的一個(gè)屬性進(jìn)行去重
這篇文章主要給大家介紹了關(guān)于java中List<對(duì)象>如何根據(jù)對(duì)象的一個(gè)屬性進(jìn)行去重的相關(guān)資料,在開(kāi)發(fā)中可能會(huì)遇到很多需要去重的情況,比如Person對(duì)象有name跟age兩個(gè)屬性,需要根據(jù)age進(jìn)行去重,需要的朋友可以參考下2023-08-08
Eclipse下編寫(xiě)java程序突然不會(huì)自動(dòng)生成R.java文件和包的解決辦法
這篇文章主要介紹了Eclipse下編寫(xiě)java程序突然不會(huì)自動(dòng)生成R.java文件和包的解決辦法 的相關(guān)資料,需要的朋友可以參考下2016-01-01
RocketMq同組消費(fèi)者如何自動(dòng)設(shè)置InstanceName
這篇文章主要介紹了RocketMq同組消費(fèi)者如何自動(dòng)設(shè)置InstanceName問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06

