Web 系統常需提供「匯出資料為文字檔」功能,如報表下載、日誌導出、代碼清單等。本文提供兩種 Spring MVC 實作範例,涵蓋基本導出與動態檔名編碼處理。
適用於簡單的列表資料導出,直接寫入 ServletOutputStream:
@RequestMapping(value = "/grab/export/csv", method = RequestMethod.GET)
public void exportCsv(HttpServletRequest request, HttpServletResponse response) {
String userId = ServletRequestUtils.getStringParameter(request, "userId", "test");
// 1. 取得業務資料
SqlVideoList sqlVideoList = new SqlVideoList();
List list = new ArrayList<>();
try {
list = sqlVideoList.selectSuccessDate(userId);
} catch (SQLException e) {
log.error("查詢資料失敗", e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// 2. 設定回應標頭
response.setContentType("text/plain; charset=UTF-8");
String fileName = "videolist";
try {
// RFC 5987 編碼,支援中文檔名
fileName = URLEncoder.encode("videolist", StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
log.warn("檔名編碼失敗,使用預設", e);
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".txt\"");
// 3. 串流寫入
try (ServletOutputStream outStr = response.getOutputStream();
BufferedOutputStream buff = new BufferedOutputStream(outStr)) {
StringBuilder write = new StringBuilder();
String enter = "\r\n"; // Windows 換行
if (!list.isEmpty()) {
for (VideoListModel model : list) {
write.append(model.getUrl()).append(",")
.append(model.getTitle())
.append(enter);
}
}
buff.write(write.toString().getBytes(StandardCharsets.UTF_8));
buff.flush();
} catch (IOException e) {
log.error("檔案寫入失敗", e);
}
}
展示更複雜的業務場景:依條件查詢、狀態轉換、分欄位輸出:
@RequestMapping(value = "/{exchangeId}/{packageId}/export", method = RequestMethod.GET)
public void writeToTxt(@PathVariable String exchangeId,
@PathVariable String packageId,
HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
String schoolId = getSchoolId(request);
// 1. 查詢資料
VipCodeExample example = new VipCodeExample();
example.createCriteria()
.andSchoolIdEqualTo(schoolId)
.andPackageIdEqualTo(packageId)
.andExchangeIdEqualTo(exchangeId);
List vipCodes = vipExchangeManager.getVipCode(example);
if (vipCodes.isEmpty()) {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
// 2. 設定回應:關鍵在於 Content-Disposition 檔名編碼
response.setContentType("text/plain; charset=UTF-8");
String downloadName = URLEncoder.encode(vipCodes.get(0).getName(), StandardCharsets.UTF_8.toString()) + ".txt";
response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
// 3. 寫入資料
try (ServletOutputStream outStr = response.getOutputStream();
BufferedOutputStream buff = new BufferedOutputStream(outStr)) {
StringBuilder write = new StringBuilder();
String tab = "\t";
String enter = "\r\n";
for (int i = 0; i < vipCodes.size(); i++) {
VipCode vipcode = vipCodes.get(i);
write.append(i + 1) // 序號
.append(tab)
.append(vipcode.getExchangeCode())
.append(tab)
.append("normal".equals(vipcode.getStatus()) ? "正常" : "已兌換")
.append(enter);
}
buff.write(write.toString().getBytes(StandardCharsets.UTF_8));
buff.flush();
} catch (IOException e) {
log.error("導出失敗", e);
}
}
| 技術點 | 說明 |
|---|---|
| Content-Type | text/plain; charset=UTF-8 明確宣告編碼,避免瀏覽器亂碼 |
| Content-Disposition | attachment 強制下載;filename* (RFC 5987) 可完美支援中文檔名 |
| 串流寫入 | 使用 BufferedOutputStream 減少系統呼叫,大量資料時效能顯著提升 |
| 資源管理 | Java 7+ try-with-resources 自動關閉串流,避免洩漏 |
| 大數據量 | 若資料超大,建議分頁查詢 + 分批寫入,避免 OOM |
若導出耗時超過 30 秒,建議採用非同步模式:
文字檔導出核心在於:正確設定 HTTP 標頭、指定 UTF-8 編碼、使用緩衝串流高效寫入、妥善處理中文檔名。掌握這兩個範例模式,即可應付 90% 的導出需求。