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.
Reader Level:

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();
    }

 

Login to add your contents and source code to this article
post comment
     

This is really nice articlehttp://www.dotnetpools.com/Article/ArticleDetiail/?articleId=22&title=Gridview%20Export%20To%20Excel%20In%20Asp.Net%20C#

Posted by vinay singh Sep 30, 2012
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts