Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert gridview data to excel sheet in asp .net with C# lang

I want to covnvert GridView data to Excel sheet.

I have written the code below, but it gives error:

protected void Button1_Click(object sender, EventArgs e) 
{       
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=Avukat.xls");
    Response.Charset = "";

    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    GridView1.RenderControl(htmlWrite);
    Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
    Response.Write(stringWrite.ToString());
    Response.End();
}

Error:

Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

like image 327
lucky One Avatar asked Jul 04 '11 05:07

lucky One


1 Answers

I think your gridview contains a linkbutton/Imagebutton or another type of control, and that's why you are getting an Exception when you are trying to export the GridView to Excel.

Before using the control you need to add the following lines in your Page code behind, or the BasePage code behind.

public override void VerifyRenderingInServerForm(Control control)
{
}

You can use this code, as this code is tested and worked perfectly:

System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Response.AddHeader("content-disposition", "attachment; filename=Avukat.xls");
Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
like image 180
Muhammad Akhtar Avatar answered Oct 03 '22 06:10

Muhammad Akhtar