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

原文地址:https://www.cnblogs.com/songrun/p/2171519.html