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

ASP.NET GridView 資料綁定與匯出 Excel 完整教學

     編輯:關於ASP.NET

前言

在 ASP.NET Web Forms 開發中,GridView 是最常用的資料呈現控制項之一。本文將示範如何從 SQL Server 讀取資料、綁定至 GridView,並實作「匯出 Excel」功能,提供完整的程式碼範例供參考。

資料庫連線與資料綁定

首先在 Page_Load 事件中建立資料庫連線,使用 SqlDataAdapter 填充 DataSet,再指定給 GridView 的 DataSource 屬性並呼叫 DataBind()。

protected void Page_Load(object sender, EventArgs e)
{
    string sqlconn = "Server=.; DataBase=db; Integrated Security=SSPI";
    string sql = "select top 10 * from table";

    using (SqlConnection myConnection = new SqlConnection(sqlconn))
    {
        myConnection.Open();
        SqlCommand myCommand = new SqlCommand(sql, myConnection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = myCommand;

        DataSet myDs = new DataSet();
        adapter.Fill(myDs);

        GridView1.DataSource = myDs.Tables[0].DefaultView;
        GridView1.DataBind();
    }
}

匯出 Excel 核心方法

DataToExcel 方法負責將 GridView 渲染為 HTML 表格並透過 HTTP 回應輸出為 .xls 檔案。關鍵在於設定正確的 Content-Type、Content-Disposition 與編碼,並覆寫 VerifyRenderingInServerForm 以避免「控制項必須置於 runat=server 的表單中」錯誤。

public void DataToExcel(string fileName, GridView myGridView)
{
    Response.Clear();
    Response.Buffer = false;
    Response.Charset = "GB2312";
    Response.AppendHeader("Content-Disposition", 
        "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + ".xls");
    Response.ContentEncoding = Encoding.GetEncoding("utf-8");
    Response.ContentType = "application/ms-excel";
    this.EnableViewState = false;

    using (StringWriter sw = new StringWriter())
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        myGridView.RenderControl(hw);
        Response.Write(sw.ToString());
    }
    Response.End();
}

// 必須覆寫,否則會拋出驗證錯誤
public override void VerifyRenderingInServerForm(Control control) { }

按鈕點擊觸發匯出

在前端放置一個 Button 控制項,於 Click 事件呼叫 DataToExcel 即可。

protected void Button1_Click(object sender, EventArgs e)
{
    DataToExcel("測試的Excel", GridView1);
}

注意事項

  • 匯出的 .xls 實為 HTML 表格,Excel 開啟時會出現格式不符警告,但可正常讀取。
  • 若資料量大,建議改用 EPPlus 或 NPOI 套件產生真正的 Excel 二進位檔案。
  • 生產環境請將連線字串存放於 Web.config,並使用參數化查詢防止 SQL Injection。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved