In order to export Gridview to Excel we need to take care of following:-
1. on top of the page - enableEventValidation ="false"
2. following is to convert into excel
protected void Button2_Click(object sender, EventArgs e)
{
string style = @"<style> .text { mso-number-format:\@;border:.5pt solid black; } </style> ";
string attachment = "attachment; filename=Report.xls";
Response.ClearContent();
Response.Write("<center>");
Response.Write("Gross Profit Report");
Response.Write("</center>");
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
3. put following code:
public override void VerifyRenderingInServerForm(Control control) {
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. */ }