ASP 透過設定 Response.ContentType 與 Response.AddHeader "Content-Disposition",可直接輸出 Word、Excel、純文字檔案供瀏覽器下載,無需實體建立檔案。
<%
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 相關更新可解決。
<%
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)。
<%
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-Type | application/msword, application/vnd.ms-excel, text/plain, application/pdf | 告知瀏覽器檔案類型 |
Content-Disposition | attachment;filename="xxx.doc" | 觸發下載對話框,指定預設檔名 |
Charset | UTF-8, Big5 | 指定字元編碼,避免中文亂碼 |
Response.Flush,避免記憶體耗盡。Response.CacheControl = "no-cache"、Response.AddHeader "Pragma", "no-cache"。EPPlus (C#)、PhpSpreadsheet (PHP) 產生真正的 .xlsx/.docx (OOXML 格式),相容性與功能更完整。