Save the html table to Excel


I see this question has been asked quite a few times before but just in case it may have escaped some eyes I state the problem again

Our ASP.Net web app displays some reports rendered as onscreen html tables and we also have export functionality. It's a standard code

Table a = new Table();

Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

So far so good. The problem is, when exporting to excel it actually gets saved as html, so when the file is opened by Excel, it comes up with the warning saying the format is not correct. It was not much of a problem as after the warning the file will open.

But with IE11 sometimes these files refuse to open saying format is not correct. As IE11 will be rolled out to more and more user, we will have to fix this problem. The options I have are

  1. Find a way to save it as XLS file and not HTML
  2. Rewrite the entire output as excel when click on export instead of rendering the output of the control to excel. We do use Aspose in our project, so I can go that way

I did try to find out, but couldn't find any thing that lets you save the content as actual xls data and not html. I am sure this is a very generic problem, so if anyone have any solution or suggestion on the same.

If nothing works I will have to go with option 2 which is more work considering the formatting and styling.

You can import HTML table to excel using Aspose.Cells. The data from HTML table will be imported, however, you will be required to take care of the table formatting.

//table.txt contains HTML table
string contents = File.ReadAllText(@"C:\data\table.txt");

using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(contents)))
    var loadOptions = new LoadOptions(LoadFormat.Html)
        ConvertNumericData = false

    //Load the HTML, this will import all the HTML table data to Excel file
    var workbook = new Workbook(stream, loadOptions);

    //Adding a new List Object to the worksheet, after this you can format the table
    Aspose.Cells.Tables.ListObject listObject = workbook.Worksheets[0].ListObjects[workbook.Worksheets[0].ListObjects.Add("A3", "E23", true)];

    //Adding predefined Style to the table
    listObject.TableStyleType = Aspose.Cells.Tables.TableStyleType.TableStyleMedium10;

    //Save using Response
    workbook.Save(this.Response, "Customer.xls", ContentDisposition.Inline, new XlsSaveOptions());

Hope this helps.