GridView to Excel

1.EnableEventValidation = "false"

<%@ Page Language="VB" EnableEventValidation = "false" AutoEventWireup="false" CodeFile="frmNextPlan.aspx.vb" Inherits="frmTrainRecord" %>

2.Code:

 Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim style As String = "<style> .text { mso-number-format:\@; } </script> "

        Response.ClearContent()
        Response.Buffer = True
        Response.Charset = "GB2312"
        Response.ContentEncoding = System.Text.Encoding.UTF8
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls")

        Response.ContentType = "application/excel"

    '防止乱码关键
        Response.Write("<meta http-equiv=Content-Type content=text/html; charset=utf-8>")

        Dim sw As New StringWriter()

        Dim htw As New HtmlTextWriter(sw)
        GridView1.AllowPaging = False
        GridView1.DataBind()
        GridView1.RenderControl(htw)

        ' Style is added dynamically

        Response.Write(style)

        Response.Write(sw.ToString())

        Response.End()
        GridView1.AllowPaging = True
        GridView1.DataBind()
    End Sub

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)


    End Sub

posted @ 2011-09-08 16:12  自由的企鹅  阅读(268)  评论(0编辑  收藏  举报