需求:用戶請求 /sqlExcel/goods.xls,下載彈窗顯示「主表.xls」。
public void DownloadExcel() {
string filePath = Server.MapPath("~/sqlExcel/goods.xls");
if (!System.IO.File.Exists(filePath)) {
Response.StatusCode = 404; return;
}
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
// 關鍵:指定下載文件名,UTF-8 編碼防中文亂碼
string fileName = "主表.xls";
string encodedName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{encodedName}\"; filename*=UTF-8''{encodedName}");
Response.TransmitFile(filePath); // 高效發送文件,不佔用內存
Response.End();
}
| Header | 作用 |
|---|---|
Content-Type | 告知瀏覽器文件類型,觸發下載而非預覽 |
Content-Disposition: attachment | 強制下載彈窗,而非瀏覽器內打開 |
filename="..." | 舊瀏覽器兼容,需 UrlEncode |
filename*=UTF-8''... | RFC 5987 標準,現代瀏覽器正確顯示中文 |