將gridview匯出為excel的簡易方法
- 1、在 ASP 的 Page 宣告多加「EnableEventValidation = "false"」屬性。
- 2、匯出的程式如下。
{
string sFilename = "filename.xls";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + sFilename);
HttpContext.Current.Response.Write("");
//先把分頁關掉,重新Bind gridview
GridView1.AllowPaging = false;
GetData();
//Get the HTML for the control.
GridView1.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
//將分頁打開,再重新Bind gridview
GridView1.AllowPaging = true;
GetData();
}
- 3、最後必須覆寫 Page.VerifyRenderingInServerForm。
public override void VerifyRenderingInServerForm(Control control)
{
}
如果不針對欄位設定、格式轉換、指定資料格式等動作以上是簡易的匯出方式。 ^^
沒有留言:
張貼留言