ViewState ["OutPut"] = ""; // defines a variable to store query conditions.
/// <Summary>
/// Create a new Gridview for export
/// </Summary>
/// <Param name = "where"> export condition </param>
Private GridView OutPutBinder (string where)
{
GridView uxGridViewOutPut = new GridView ();
UxGridViewOutPut. DataSource = CardBLL. GetALL (where ,"");
UxGridViewOutPut. DataBind ();
Return uxGridViewOutPut;
}
/// <Summary>
/// Export to EXCEL
/// </Summary>
/// <Param name = "FileName"> exported file name </param>
Public void OutPutExcel (string FileName)
{
Response. Clear ();
Response. Buffer = true;
Response. Charset = "GB2312 ";
Response. AppendHeader ("Content-Disposition", "attachment; filename =" + FileName + ". xls ");
Response. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
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 );
OutPutBinder (ViewState ["OutPut"]. ToString (). RenderControl (oHtmlTextWriter );
// This indicates that the current page is output. You can also bind the datagrid or other controls that support the obj. RenderControl () attribute.
Response. Write (oStringWriter. ToString ());
Response. End ();
}
Public override void VerifyRenderingInServerForm (Control control Control)
{
}
The following error occurs when "export data from the GridView to Excel" is implemented:
User code does not handle InvalidOperationException
RegisterForEventValidation can be called only during Render () execution;
The EnableEventValidation attribute is. NET Framework 2.0 is a new property. By default, the value of this property is true. ASP. NET checks the parameters in the POST method. If it is deemed invalid, an exception is thrown. The purpose of this design is to prevent malicious users from using the post method to send malicious data, but sometimes there are similar errors.
If this function is disabled, the problem can be solved. You can solve this problem in two ways:
1. In the Web. Config file: Add the following code in the <system. web> </system. web> tag:
<System. web>
<Pages enableEventValidation = "false"> </pages>
</System. web>
2. modify the code in the source code of the. aspx page as follows:
<% @ Page Language = "C #"
EnableEventValidation = "false"AutoEventWireup = "true" CodeFile = "GridView_Export_Excel.aspx.cs" Inherits = "GridView_Export_Excel" %>