Reader Level:
ARTICLE

Export ASP.NET Gridview data into MS-Excel sheet

Posted by Vamshi Krishna Articles | ASP.NET Programming March 29, 2011
Here you will see how to Export ASP.NET Gridview data into MS-Excel sheet.
  • 0
  • 0
  • 9298

Export ASP.NET Gridview data into MS-Excel sheet

  • Prepare Database, table, and insert data into table.
  • Bind table data in to ASP.Net Gridview (gridview name "gvPrint") data control.

    MS.gif

HtmlForm class:

HtmlForm provides programmatic access to the HTML <form> element on the server through the set of properties.

Namespace:
using System.Web.UI.HtmlControls;

Code under Print button:


protected void btnPrint_Click(object sender, EventArgs e)
    {
        ExportFromHtmlForm(gvPrint);      
    }

public void ExportFromHtmlForm(GridView gv)
    {
        HtmlForm form = new HtmlForm();

        string attachment = "attachment; filename=PrintDetails.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";

        //namespace (using system.IO)     
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);

        gv.Parent.Controls.Add(form);
        form.Attributes["runat"] = "server";
        form.Controls.Add(gv);
        this.Controls.Add(form);
        form.RenderControl(htextw);
        Response.Write(stw.ToString());

         Response.End();
    }

 

COMMENT USING

Trending up