views:

558

answers:

2

I have an ASP.Net MVC site that generates a Microsoft Excel 2003 XML formatted spreadsheet. The spreadsheet looks good, the controller and views both work, but the file won't open in Excel. It opens in the browser because it is an XML document.

I tried changing the ContentType to be the Excel XLS format (application/excel) and that made Excel open the file but it gives a warning message that the file is an XML document, not an XLS document.

How do you make an Excel XML document open in Excel from a web site?

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %><%  
this.Context.Response.Clear();  
this.Context.Response.AddHeader("content-disposition", "attachment;filename=State_Report_" + this.ViewData["State"] + ".xml");  
this.Context.Response.Charset = "";  
this.Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);  
this.Context.Response.ContentType = "application/excel";  
%><?xml version="1.0"?>  
<?mso-application progid="Excel.Sheet"?>  
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"  
  xmlns:o="urn:schemas-microsoft-com:office:office"  
  xmlns:x="urn:schemas-microsoft-com:office:excel"  
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"  
  xmlns:html="http://www.w3.org/TR/REC-html40"&gt;
+1  A: 

Your problem may be in using the file extension .xml, which you're adding in your header. My code that does this same thing does not have a file extension at all.

You might try dropping that .xml extension, or changing it to .xls or .csv.

DOK
First of all, thank you DOK. I tried this and the file now opens in MS Excel but it then gives an error message saying that the file format does not match the extension since I have used the XML format in a file with a .XLS extension. I think my user can live with this, but I would prefer to make it work without a warning message.
Mark Ewer
How about .xlsx? That's the newer extension introduced in Excel 2007. This has another suggestion, which may or may not be palatable: http://www.itexperience.net/2008/03/17/excel-2007-error-different-format-than-specified-by-the-file-extension/
DOK
It's not pretty, but the customer accepted it...
Mark Ewer
+1  A: 

Try with

Response.ContentType = "application/vnd.ms-excel"

And keep the .XML extension.

Eduardo Molteni
See: http://support.microsoft.com/kb/288130
chrisb