萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 產生 Word/Excel/文字檔下載:Response.ContentType 完整實作

ASP 透過設定 Response.ContentType 與 Response.AddHeader "Content-Disposition",可直接輸出 Word、Excel、純文字檔案供瀏覽器下載,無需實體建立檔案。

1. 產生 Word 檔 (.doc)

<%
Response.ContentType = "application/msword"
Response.AddHeader "Content-Disposition", "attachment;filename=export.doc"
Response.Charset = "UTF-8"
%>
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body>
<h1>這是 Word 文件標題</h1>
<p>內容段落...</p>
<table border="1"><tr><td>儲存格</td></tr></table>
</body></html>

常見問題: 開啟時提示「需要轉換器」,通常因 Office 版本缺少特定濾鎖器。重裝 Office 或安裝 SKU011.CAB 相關更新可解決。

2. 產生 Excel 檔 (.xls)

<%
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=report.xls"
Response.Charset = "UTF-8"
%>
<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body>
<table border="1">
  <tr><th>欄位1</th><th>欄位2</th></tr>
  <tr><td>資料1</td><td>資料2</td></tr>
  <tr><td>資料3</td><td>資料4</td></tr>
</table>
</body></html>

Excel 會自動將 HTML 表格解析為儲存格。若需進階格式 (合併儲存格、公式、樣式),建議改用 Excel.Application COM 物件或第三方元件 (如 Aspose.Cells)。

3. 產生純文字檔 (.txt)

<%
Response.ContentType = "text/plain"
Response.AddHeader "Content-Disposition", "attachment;filename=log.txt"
Response.Charset = "UTF-8"

' 使用 FSO 讀取現有檔案內容
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile(Server.MapPath("data.log"), 1) ' 1=ForReading
Response.Write file.ReadAll
file.Close
Set file = Nothing
Set fso = Nothing
%>

或直接輸出字串:Response.Write "第一行" & vbCrLf & "第二行"

關鍵標頭說明

標頭值範例作用
Content-Typeapplication/msword, application/vnd.ms-excel, text/plain, application/pdf告知瀏覽器檔案類型
Content-Dispositionattachment;filename="xxx.doc"觸發下載對話框,指定預設檔名
CharsetUTF-8, Big5指定字元編碼,避免中文亂碼

注意事項

  • 輸出前不可有任何 HTML 輸出 (含空白行、BOM),否則檔案會被汙染。
  • 大量資料建議分塊 Response.Flush,避免記憶體耗盡。
  • IE 緩存問題:加 Response.CacheControl = "no-cache"、Response.AddHeader "Pragma", "no-cache"。
  • 現代替代:伺服器端用 EPPlus (C#)、PhpSpreadsheet (PHP) 產生真正的 .xlsx/.docx (OOXML 格式),相容性與功能更完整。
copyright © 萬盛學電腦網 all rights reserved