延續上篇,本文彙整兩種經典匯出入口:DataSet/DataTable 為來源與GridView 等控制項為來源。
支援同時匯出 Excel (Tab 文字) 或 XML 格式:
public void CreateExcel(DataSet ds, string typeId, string fileName)
{
HttpResponse resp = HttpContext.Current.Response;
resp.ContentEncoding = Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
DataTable dt = ds.Tables[0];
DataRow[] rows = dt.Select("");
if (typeId == "1") // Excel (Tab 文字)
{
// 標題
string header = string.Join("\t", dt.Columns.Cast().Select(c => c.Caption));
resp.Write(header + "\n");
// 資料
foreach (DataRow row in rows)
{
string line = string.Join("\t", row.ItemArray.Select(o => o.ToString()));
resp.Write(line + "\n");
}
}
else if (typeId == "2") // XML
{
resp.Write(ds.GetXml());
}
resp.End();
}
適用於已繫結資料的 GridView、DataList、Repeater 等:
public void ExportControl(Control ctrl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Export.xls");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = Encoding.Default;
ctrl.Page.EnableViewState = false;
using (var sw = new StringWriter())
using (var hw = new HtmlTextWriter(sw))
{
ctrl.RenderControl(hw);
HttpContext.Current.Response.Write(sw.ToString());
}
HttpContext.Current.Response.End();
}
// 使用:ExportControl(GridView1);
VerifyRenderingInServerForm 回傳 void,或確認控制項在 <form runat="server"> 內。ContentEncoding = Encoding.GetEncoding("GB2312") 或 UTF-8,並對檔名 UrlEncode。SaveAs 到 MemoryStream) 避免字串拼接。新專案優先採用 EPPlus / ClosedXML / NPOI 產生真正 .xlsx,避免格式相容性問題,並支援樣式、凍結窗格、資料驗證等企業級需求。