在透過使用Visual Studio 2005中的Gridview 將呈現資料時,使用

者常要求將資料輸出至Excel或Word 文件中,要怎麼做呢?


將GridView 匯出至Excel 這個問題,從早期Visual Studio

2002/2003中的Grid 就有解決方案了,但在GridView中則有少許

變化, 詳細的語法如下:

VB語法

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = "big5"
Response.ContentType = "application/vnd.xls"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
GridView1.RenderControl(htmlWrite) <--非GridView1請更改為要輸出名稱
Response.Write(stringWrite.ToString)
Response.End()

End Sub
務必加入下段語法
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

'Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

End Sub

C#語法

protected void Button1_Click(object sender, EventArgs e)
    {
         Response.Clear();
         Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
         Response.Charset = "big5";
         Response.ContentType = "application/vnd.xls";
         System.IO.StringWriter stringWrite = new System.IO.StringWriter();
         System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
         GridView1.AllowPaging = false;
         GridView1.AutoGenerateEditButton = false;
         GridView1.AutoGenerateDeleteButton = false;
         GridView1.DataBind();
         GridView1.RenderControl(htmlWrite);
         Response.Write(stringWrite.ToString());
         Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
        server control at run time. */
    }

同樣的如果要將GridView資料輸出至Word文件,只要將

FileName.xls 改為 FileName.doc 及 application/vnd.xls 改為 application/vnd.doc

就可將資料輸出至Word文件中

例:
<%

相关文章:

  • 2021-08-26
  • 2021-07-16
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
猜你喜欢
  • 2022-01-16
  • 2022-01-15
  • 2022-12-23
  • 2022-12-23
  • 2022-02-05
  • 2021-08-24
  • 2021-09-28
相关资源
相似解决方案