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:

  1. Response.AppendHeader("content-disposition""attachment;filename=ExportedHtml.xls");  
  2. Response.Charset = "";  
  3. Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  4. Response.ContentType = "application/vnd.ms-excel";  
  5. this.EnableViewState = false;  
  6. Response.Write(YOURHTMLGOESHERE);  
  7. Response.End(); 

Detailed description

My web page looks like this:

Image 1.jpg

Now for the code behind, the button click event:

  1. protected void ExportToExcelButton_Click(object sender, EventArgs e)  
  2. {  
  3.         Response.AppendHeader("content-disposition""attachment;filename=ExportedHtml.xls");  
  4.         Response.Charset = "";  
  5.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  6.         Response.ContentType = "application/vnd.ms-excel";  
  7.         this.EnableViewState = false;  
  8.         Response.Write(ExportDiv.InnerHtml);  
  9.         Response.End();  
  10. }
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:


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


Hope that will help someone.

Note: a running sample is attached.