2013年9月25日 星期三

gridview匯出EXCEL


Imports System.IO
Imports System.Web
Imports System.Text

Partial Class GridView_Excel
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Clear()
        Response.Buffer = True
        Response.Charset = "BIG5"
        Response.AppendHeader("Content-Disposition", "attachment;filename=test_file_" & FormatDateTime(Now, DateFormat.ShortTime) & ".xls")
        Response.ContentEncoding = Encoding.GetEncoding("BIG5")
        Response.ContentType = "application/ms-excel "
        GridView1.EnableViewState = False
        Dim objStringWriter As New StringWriter
        Dim objHtmlTextWriter As New UI.HtmlTextWriter(objStringWriter)
        '--註解:或是寫成 Dim objHtmlTextWriter As UI.HtmlTextWriter = New UI.HtmlTextWriter(objStringWriter)
        GridView1.RenderControl(objHtmlTextWriter)
        Response.Write(objStringWriter.ToString())
        Response.End()
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        '處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
    End Sub
End Class

沒有留言:

張貼留言