Export HTML to Excel and More

I was working on a project where I had a grid-like table structure with a number of columns and values, and the requirement was to export data to Excel. I want to share the solution that I implemented here with you, hoping it might help someone.

Here we go.

The following code block is what you need:

        Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");

        Response.Charset = "";

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.ms-excel";

        this.EnableViewState = false;

        Response.Write(YOURHTMLGOESHERE);

        Response.End();

Detailed description

My web page looks like this:

Image 1.jpg

Now for the code behind, the button click event:

protected void ExportToExcelButton_Click(object sender, EventArgs e)

{

        Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");

        Response.Charset = "";

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.ms-excel";

        this.EnableViewState = false;

        Response.Write(ExportDiv.InnerHtml);

        Response.End();
}


Where ExportDiv is the HTML "div" element that contains the HTML (as can be seen in the preceding screenshot). Now on clicking the "Export To Excel" button, the contents will be copied to a newly generated Excel file, which will look like:

Image 2.jpg

That's it; we are sorted.

Now one problem that we generally encounter when an Excel is downloaded via http is the following error message that pops up if we download an Excel over http (especially for MSOffice 2007+ versions):

Which is really annoying.

More details can be found at:

http://forums.asp.net/t/1070490.aspx/3/10

And the solution for it can be found in a nice article at:

http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

Hope that will help someone.

Note: a running sample is attached.

Up Next
    Ebook Download
    View all
    Learn
    View all