Home » excel » html – Export to Excel from ASP.NET produces files unreadable with Excel Viewer

html – Export to Excel from ASP.NET produces files unreadable with Excel Viewer

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to output some dynamic data from an ASP.NET website to Excel. I found that the easiest way which does not require to use Excel XML or to install Excel on server machine is to output data as a table and specify application/vnd.ms-excel type.

The problem is when I do so and try to open the file in Excel Viewer, I receive the following error message:

Microsoft Excel Viewer cannot open
files of this type.

Then nothing is opened.

Even an easiest code such as:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Example.xls");
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter stringWriter = new System.IO.StringWriter();
    HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
    dataGrid.RenderControl(htmlTextWriter);
    Response.Write("<html><body><table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table></body></html>");
    Response.End();
}

produces the same error.

What can cause such behavior? Is it because the Viewer cannot read such files, but full Excel version can?

How to&Answers:

Excel reader can only open excel files. You really aren’t exporting it as an excel file, you are exporting it as a csv or html. It’s not the same.

EDIT

Have you tried this Export to Excel?

Answer:

You never, ever want to go down the route of installing Excel on the server. The COM interface can work without the UI, but it’s not designed to do, and you can end up with a large number of hung EXCEL.EXE instances on your server if there is an error of some sort. It also plain doesn’t work with IIS 7.5’s application pool identites, nor does it work with Server Core.

The ideal solution is to use a third-party component that can build binary (or OOXML) Excel files. SyncFusion and Aspose are two major vendors of such tools. You’ll end up with files that will work all versions of Excel, as well as in other software such as OpenOffice, Google Docs, Outlook Web App, and so on.