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

ASP.NET 利用 GridView 匯出 Excel 檔案完整範例

     編輯:關於ASP.NET

透過 GridView 將資料匯出為 Excel 是常見需求。核心概念:建立含 GridView 的 ASPX 頁面,後台繫結資料後,在 Page_Load 或按鈕事件中直接輸出 HTML 表格並設定回應標頭使瀏覽器另存為 .xls。

前台 GridView 範例

<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 套件,相容性佳,適合伺服器環境。

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