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

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.

srinu vasPosted May 5, 2022, 5:12 PM
Thank you nice article
Munesh VarshneyPosted Apr 6, 2017, 2:20 AM
Sir I want To Export html to Excel in multiple Sheets . Please help me .
Pankaj KadamPosted May 7, 2016, 5:05 AM
plz help
Pankaj KadamPosted May 7, 2016, 5:05 AM
i have html <div> contains user info and his profile image that i want to export as it is in PDF
veera muthuPosted Sep 5, 2015, 3:31 AM
ExportDiv.innerHtml showing error...i need solution
uthira samyPosted Jan 6, 2015, 5:24 AM
SCRIPT438: Object doesn't support property or method 'btoa'
Fauzan FebriPosted Aug 5, 2014, 11:40 PM
How can I format the excel file after exported? Like Font size, color, add image, etc. Is it possible if its done after clicking export button?