如何在將Datagrid的資料存成Excel列出

摘要:如何在將Datagrid的資料存成Excel列出

按下button產生Excel檔,(好像是直接下載)
將你DataGrid的html輸出到HtmlText
而HtmlText使用StringWriter的資料

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(sw) 
Response.Clear()
Response.AppendHeader("Content-Disposition", "attachment; filename=P.xls")
Response.ContentType = "application/vnd.ms-excel"

GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub

'一定要加這一段,否則會有驗證問題
Public Overrides Sub VerifyRenderingInSer verForm(ByVal control As Control)
'處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
End Sub