在 ASP.NET 中匯出 Excel 主要有兩大策略:一是將整個 HTML 頁面(含按鈕、分頁等)輸出;二是僅匯出特定控制項(如 DataGrid)的資料。關鍵在於設定 Response.ContentType = "application/ms-Excel"(或 application/vnd.ms-Excel"),瀏覽器即會提示下載而非直接顯示。
最簡單的方式,將頁面所有內容視為 Excel 資料。缺點是會包含不需要的 UI 元素。
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-Excel";
this.EnableViewState = false;
ContentType 也可設為 image/JPEG、text/Html、application/msword 等,分別匯出圖片、HTML、Word 文件。
利用 RenderControl 將 DataGrid 轉為 HTML 字串再輸出。若 DataGrid 有分頁,僅會匯出當前頁面顯示的資料。
System.Web.UI.Control ctl = this.DataGrid1;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-Excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-Excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
// 使用方式:DGToExcel(DataGrid1);
此兩種方法屬於「偽 Excel」匯出,實際上是輸出 HTML 表格由 Excel 開啟。優點是無需安裝 Office 組件,缺點是無法支援真正的 Excel 功能(公式、多工作表、儲存格格式等)。進階需求請參考後續文章的 COM 或 OpenXML 方案。