在 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();
}
}
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);
}
EPPlus 或 NPOI 套件產生真正的 Excel 二進位檔案。Web.config,並使用參數化查詢防止 SQL Injection。