透過 GridView 將資料匯出為 Excel 是常見需求。核心概念:建立含 GridView 的 ASPX 頁面,後台繫結資料後,在 Page_Load 或按鈕事件中直接輸出 HTML 表格並設定回應標頭使瀏覽器另存為 .xls。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ...>
<Columns>
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:BoundField DataField="Sex" HeaderText="性別" />
<asp:BoundField DataField="BirthDay" HeaderText="出生日期" />
<asp:BoundField DataField="StudentId" HeaderText="身份證號" />
...
</Columns>
</asp:GridView>
private void Export(string fileType, string fileName) {
// 將指定欄位設為文字格式,防止長數字科學記號
for (int i = 0; i < GridView1.Rows.Count; i++) {
GridView1.Rows[i].Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
Response.ContentType = fileType; // 如 "application/ms-excel"
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
// 必須覆寫,否則 RenderControl 會拋出例外
public override void VerifyRenderingInServerForm(Control control) { }
此法無需安裝 Office 套件,相容性佳,適合伺服器環境。