/// <summary> ///implementation to export data to Excel,///In the above code, we first bind the GridView to the specified data source, and then write the relevant code in the event of the Button1 button (used to export to Excel). ///here Use Response.AddHeader ("Content-disposition", "attachment;filename= Exporttoexcel.xls"); To specify the file name of the Excel that will be exported,///this is Exporttoexcel.xls. Note that because the contents of the GridView may be paginated, the AllowPaging property of the GridView is set to false each time you export Excel .///You then export the current page's GridView to Excel through the page flow, and then reset its AllowPaging property. Also note that to write an empty Verifyrenderinginserverform method (must write),///to confirm that the HtmlForm control is rendered for the specified ASP. NET server control at run time/// **************************************************************** ///The following code section is from the Internet///Export data to filename.xls*****************/// </summary> /// <param name= "Sender" ></param> /// <param name= "E" ></param> protected voidButton1_Click (Objectsender, EventArgs e) {response.clear (); Response.AddHeader ("content-disposition","Attachment;filename=filename.xls"); Response.Charset="gb2312"; Response.ContentType="Application/vnd.xls"; System.IO.StringWriter Stringwrite=NewSystem.IO.StringWriter (); System.Web.UI.HtmlTextWriter Htmlwrite=NewHtmlTextWriter (Stringwrite); This. GridView1. AllowPaging =false; This. bind (); This. GridView1. RenderControl (Htmlwrite); Response.Write (Stringwrite.tostring ()); Response.End (); This. GridView1. AllowPaging =true; This. bind (); }
When the code is finished, the data is exported with an error: The registerforeventvalidation can only be called during Render () execution
So Baidu, on the corresponding page, plus enableeventvalidation= "false", problem solving.
Reference RELATED Links: http://www.ezloo.com/2008/10/render_registerforeventvalidation.html
In the atom, if you find a problem, or have a better way, welcome to shoot Bricks!
C # Export data to Excel