Export to Excel from ASP.NET produces files unreadable with Excel Viewer
- by MainMa
Hi,
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?