How to export Excel uisng HtmlForm(GridView) object in asp.net

Today I want to show you another way how to export Excel file from HtmlForm object. This is a serial post for How to export Excel file. Using HtmlForm object we should  use a Control which is rendering by HtmlTextWriter.

In this article, I use the GridView control. Here I provide a method where you pass a GridView control as parameter after that this method render this gridview control as a excel file from html object.

Code:C#

Namespace:
using System.Web.UI.HtmlControls 


public void ExportFromHtmlForm(GridView gvEmployee)
    {
        HtmlForm form = new HtmlForm();
        string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        form.Controls.Add(gvEmployee);
        this.Controls.Add(form);
        form.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();
    }

Comments

Huck said…
Thanks, used this code. Nice & tidy!
Anonymous said…
This works fine with a simple table, I have a table where I have added an extra header row as part of the grid bind and the export dows not include the extra row and is dropping the last data row.

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript