首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET (C#) 讀取與輸出 Word 文件的三種實作方法

     編輯:ASP.NET 基礎

前言:伺服端輸出 Word 的核心機制

ASP.NET 輸出 Word 文件本質上是:設定正確的 MIME 類型 → 讀取檔案二進位流 → 寫入 HTTP 回應流。關鍵在於 Content-Type 設為 application/msword,並可選擇性加上 Content-Disposition 標頭控制瀏覽器行為(直接開啟或另存新檔)。

方法一:Response.WriteFile 直輸法(最簡潔)

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/msword";
string path = Server.MapPath("C#語言參考.doc");
Response.WriteFile(path);
Response.Flush();
Response.Close();

特點:一行 WriteFile 完成讀取與輸出,適合小檔案、簡單下載情境。但無法自訂下載檔名(瀏覽器會用原檔名或 URL 尾段)。

方法二:FileStream 手動控制流(可指定位移與長度)

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/msword";
string path = Server.MapPath("C#語言參考.doc");
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
Response.WriteFile(path, 0, fs.Length); // 可控制 offset 與 length
fs.Close();

進階用途:WriteFile 多載支援 offset 與 length 參數,可實現斷點續傳或分段輸出大檔案,減少記憶體壓力。

方法三:完整二進位陣列輸出法(支援自訂下載檔名)

string path = Server.MapPath("C#語言參考.doc");
FileInfo file = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] fileData = new byte[file.Length];
fs.Read(fileData, 0, (int)file.Length);
fs.Close();

Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=自訂檔名.doc");
Response.BinaryWrite(fileData);
Response.End();

關鍵優勢:

  • Content-Disposition: attachment;filename=... 強制瀏覽器彈出「另存新檔」對話框,且可自訂下載檔名(解決中文檔名編碼問題)
  • BinaryWrite 直接寫入位元組陣列,避免文字編碼轉換錯誤
  • Response.End() 立即終止管線,確保無額外輸出干擾

三種方法比較與選擇指南

維度方法一 WriteFile方法二 FileStream+WriteFile方法三 BinaryWrite
程式碼複雜度最低中等較高
自訂下載檔名❌❌✅
大檔案支援⚠️ 記憶體壓力大✅ 可分段讀取⚠️ 需完整載入記憶體
斷點續傳潛力❌✅ 配合 Range 標頭❌
適用情境小檔、簡單下載大檔、需流控需自訂檔名、中文檔名

實務增強:大檔案分塊輸出(避免 OOM)

Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=大檔.doc");
Response.BufferOutput = false; // 關閉緩衝,即時輸出

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) {
    byte[] buffer = new byte[8192]; // 8KB 緩衝區
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
        Response.OutputStream.Write(buffer, 0, bytesRead);
        Response.Flush(); // 即時推送給客戶端
    }
}
Response.End();

此模式不將整檔載入記憶體,適合 100MB+ 的大型 Word 文件輸出,配合 Response.BufferOutput = false 實現真正的串流傳輸。

常見坑點與解決方案

  • 中文檔名亂碼:filename=" + HttpUtility.UrlEncode("中文檔名.doc", Encoding.UTF8) + "(現代瀏覽器支援 RFC 5987 格式:filename*=UTF-8''...)
  • 輸出檔案損毀:確認 Response.Clear() 清除前置輸出,避免 HTML/空白字元混入二進位流
  • 權限問題:應用程式池身分需具備檔案讀取權限
  • 並發大量下載:考慮非同步 I/O 或雲端儲存簽名 URL 導流

依據專案需求選擇適當方法,並注意記憶體管理與編碼細節,即能穩健實作 Word 文件下載功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved