user979331
user979331

Reputation: 11851

ASP.NET MVC export html table to excel not working

I have this method here:

[Authorize]
        [HttpPost]
        [ValidateInput(false)]
        public void ExportCostMatrixExcel(string GridHtmlExcel, string GridCommunityExcel)
        {
            Response.ClearContent();
            Response.ClearHeaders();
            Response.BufferOutput = true;
            Response.ContentType = "application/excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xlsx");
            Response.Write(GridHtmlExcel);
            Response.Flush();
            Response.Close();
            Response.End();
        }

This takes me html table and converts it over to an Excel spreadsheet, when I try to open the file, I get this error message:

Excel cannot open the file 'Reliquat.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

Why is this happening, you can see GridHtmlExcel here on the link below, its an HTML table with colspans, is the colspans messing it up?

https://jsfiddle.net/2nyjhpaz/3/

Upvotes: 0

Views: 416

Answers (1)

Matt Griffiths
Matt Griffiths

Reputation: 1142

In essence it looks like you're merely dumping the contents into a file and just renaming it to an XLSX. However, that extension follows a specific XML-based schema, and that's why it doesn't play well.

You have a few options:

  1. Find a library that can do this for you - initial searches list a few but they're often fickle little beings.
  2. Use something like HTML Agility Pack to parse the HTML into a usable format and write it into an excel file. You might have to create an excel file manually, possibly using the Office Interop stuff.
  3. If the excel format itself isn't that much of an issue, you could choose to write a CSV file instead (and can be opened by excel), using CSV Helper - but you'd still have to parse the HTML.

Upvotes: 1

Related Questions