代码之家  ›  专栏  ›  技术社区  ›  Mark Ewer

在ASP.NET MVC网站中生成Excel XML文档

  •  3
  • Mark Ewer  · 技术社区  · 15 年前

    我有一个ASP.NET MVC站点,它生成一个Microsoft Excel 2003 XML格式的电子表格。电子表格看起来不错,控制器和视图都可以工作,但文件无法在Excel中打开。它在浏览器中打开,因为它是一个XML文档。

    我尝试将ContentType更改为Excel XLS格式(application/excel),这使得Excel打开了该文件,但它给出了一条警告消息,即该文件是XML文档,而不是XLS文档。

    如何使Excel XML文档从网站在Excel中打开?

    <%@ 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">  
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   DOK    15 年前

    您的问题可能在于使用文件扩展名.xml,您要在头中添加该扩展名。 执行相同操作的代码根本没有文件扩展名。

    您可以尝试删除该.xml扩展名,或者将其更改为.xls或.csv。

        2
  •  3
  •   Eduardo Molteni    15 年前

    尝试用

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

    并保留.xml扩展名。