Sunday, May 16, 2010

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

3 comments:

Huck said...

Thanks, used this code. Nice & tidy!

Unknown said...

welcome...

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.

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...