Export the gridview to an Excel file in ASP. NET 2.0
BelowCodeExport the gridview to an Excel file.
It is worth noting that the verifyrenderinginserverform overload method:
Description of the verifyrenderinginserverform Method on msdn:
The control must be located in the <form runat = Server> flag. You can call this method before rendering to Display error messages when the control is placed outside the tag. The control that sends back or relies on the registered script block should call this method in the override of the control. Render method. You can override this method for different pages that render server form elements to cause exceptions under different conditions.
If the server controls for sending back or using client scripts are not included in the htmlform Server Control (<form runat = "server">) Tag, they will not work properly. These controls can call this method during rendering to provide clear error information when they are not included in the htmlform control.
This method is usually called when the render method is rewritten for any type of input tag during custom server control development. This is especially important when the input control calls getpostbackeventreference or sends a client script. This call is not required for composite server controls.
This method is not available,ProgramAn error will be reported.
Today, I wrote a code to export data to excel and Doc. The method is as follows:
Protected void export_click (Object sender, eventargs E)
{
Response. Clear ();
Response. Buffer = true;
// Response. charset = "gb2312 ";
// Set the output file type to an Excel file.
Response. contenttype = "application/MS-excel ";
Response. appendheader ("content-disposition", "attachment?filename=boiler.xls ");
// If the encoding method is set to the following, it must be consistent with that on the top of the web. config page <? XML version = "1.0" encoding = "UTF-8"?> Consistency in
Response. contentencoding = system. Text. encoding. utf8;
System. Io. stringwriter ostringwriter = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter ohtmltextwriter = new system. Web. UI. htmltextwriter (ostringwriter );
This. gridview1.rendercontrol (ohtmltextwriter );
Response. Output. Write (ostringwriter. tostring ());
Response. Flush ();
Response. End ();
}
Export to excel and DOC:
Error prompted during running: system. Web. httpexception: the control gridview1 of the "gridview" type must be placed in the form tag with runat = server. Add:
Public override void verifyrenderinginserverform (Control)
{
}
If the prompt is: system. invalidoperationexception: registerforeventvalidation can only be called during render () execution; if the allowpaging attribute of the gridview is set to true, the enableeventvalidation = "false" attribute should be added to <% @ page Language = "C #" DEBUG = "true" %>.
So everything is OK!