Exporting gridview data into excel (.xls,.xlsx) file in asp.net c#

How to export table/gridview/datagrid to excel in asp.net :-
To export a datagrid or a gridview data we have to get rendered html in server side for that we use 'RenderControl' property of controls which gives the render html in a HtmlTextWriter and then copyied
in a StringWriter.
For exporting a table add an attribute Runat='Server' in table
MyTable = ID of Gridview/Datagrid/table (runat='server')


using System.Web.UI.HtmlControls;

protected void ExpToExl()
    {
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);


        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=ExportToExcel.xls");
        Response.ContentType = "application/excel";


        //*********Copying the randered Html in StringWriter**********
        HtmlForm H1 = new HtmlForm();
        H1.Controls.Add(MyTable);
        this.Controls.Add(H1);
        H1.RenderControl(htmlWrite);

        //**************Or Userd this*********
        // MyTable.RenderControl(htmlWrite);


        Response.Write(stringWrite.ToString());
        Response.End();

    }



Recent Article