个人学习代码保存:例12.读取GridView文件中的数据到Excel文件 前台代码:Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation = "false" %> <!--EnableEventValidation = "false" 用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。 --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出Excel" /> </form> </body> </html> 后台代码:Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { private static string connstr=ConfigurationManager.AppSettings["ConnectionString"].ToString(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.GridView1.DataSource = GetData(); this.GridView1.DataBind(); } } public DataSet GetData() { SqlConnection con = new SqlConnection(connstr); if (con.State.Equals(ConnectionState.Closed)) { con.Open(); } string sql = "select * from guestbook"; SqlCommand cmd = new SqlCommand(sql,con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds); con.Close(); return ds; } // 否则会出现:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。 public override void VerifyRenderingInServerForm(Control control) { // Confirms that an HtmlForm control is rendered for } protected void Button1_Click(object sender, EventArgs e) { ExportDataGrid("online/ms-excel", "ddd.xls"); } private void ExportDataGrid(string FileType, string FileName) { Response.Clear(); Response.Buffer = true; Response.Charset = "utf-7"; Response.AppendHeader("Content-Disposition", "attachment;filename=FileFlow.xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7"); Response.ContentType = "application/ms-excel"; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); this.GridView1.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); } }