【问题标题】:C# Excel file download corrupting file?C# Excel 文件下载损坏文件?
【发布时间】:2014-10-19 12:03:48
【问题描述】:

我编写了一些代码,将某个文件下载到用户的计算机上,这是一个 MS Excel .xlsx 文件。问题是,当用户从我的网络应用程序下载并打开文件时,我在 excel 中收到一条消息,说“我们发现 file.xlsx 中的某些内容存在问题”。然后我单击是以恢复内容,这就是日志文件显示的内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error128120_01.xml</logFileName><summary>Errors were detected in file 'F:\Downloads\file.xlsx'</summary><additionalInfo><info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info></additionalInfo></recoveryLog>

这是我用来下载 C# 文件的代码。根据我的研究,我相信这是 .xlsx 的正确 mimetype。此外,当我在文件夹资源管理器中打开文件时,仅在下载后不会出现问题。我已尝试过 Google Chrome 和 Internet Explorer。

        var fileInfo = new FileInfo(Path.Combine(Server.MapPath("~/Content/"), "file.xlsx"));
        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + "file.xlsx");
        Response.TransmitFile(fileInfo.FullName);
        Response.Flush();

有什么想法吗?

【问题讨论】:

    标签: c# asp.net-mvc excel httpresponse


    【解决方案1】:

    有时是编码问题

     var result = new StreamWriter(output); 
    

    写入输出缓冲流时不要使用任何特定的编码

    【讨论】:

    • 对编码注释的宾果游戏。不要指定编码。
    【解决方案2】:

    您是否检查过该文件实际上没有损坏?

    如果您使用的是 ASP .NET MVC,为什么不从您的操作中返回一个 FileResult?我认为这是标准的做法。

    更新 您可以让控制器通过从浏览器返回 FileResult 将文件发送到浏览器进行下载。使用 File 方法的方式与控制器中的 View 方法非常相似。

    例子:

    public ActionResult(int id)
    {
        var downloadStream = GetSomePdfStream(id);
        //note how I specified the MIME type, so that the browser knows what am I sending to it.
        return File(downloadStream, "application/pdf", "file.pdf"); 
    }
    

    有几个方便的重载可以从 byte[] 或 Stream 或路径返回文件:

    File(Stream stream, string mime, string downloadName) //returns System.Web.Mvc.FileStreamResult:FileResult
    File(string fileName, string mime, string downloadName);//returns FilePathResult:FileResult
    File(byte[] contents, string mime, string downloadName);//returns FileContentResult:FileResult
    

    【讨论】:

    • 正如我所说,在文件资源管理器中,打开文件自然不会出错。通过程序下载后,该文件有错误。如果您可以向我展示 FileResult 的方式,我可以将您的答案标记为正确?
    • 抱歉,回复晚了。我增强了答案,如果有帮助,请告诉我。
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    相关资源
    最近更新 更多