I am trying to export gridview contents into Excel as given below, Excel is created but there is no content. but I am able to view the content in the webpage.
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.AllowPaging = false;
gv.DataBind();
gv.RenderControl(hw);
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//verifies that the control is rendered
}
Loading

Rishikesh Kumar SinghRank #1,250 · 1.4K reputationPosted Feb 4, 2013, 12:04 AM EST
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
If it helps you then mark it as an accepted answer otherwise let me know..!!
JAYRAMRank #7,836 · 233 reputationPosted Feb 4, 2013, 12:23 AM EST
JAYRAMRank #7,836 · 233 reputationPosted Feb 4, 2013, 7:47 AM EST
Dscription: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.error
RegisterForEventValidation can only be called during Render();
Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();
Source Error: