C#Excel文件下载损坏的文件

本文关键字:文件 损坏 文件下载 C#Excel | 更新日期: 2023-09-27 18:26:59

我写了一些代码,可以将某个文件下载到用户的计算机上,该文件是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。此外,当我在文件夹资源管理器中打开文件时,问题不会出现,只有在下载后才会出现我试过谷歌浏览器和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#Excel文件下载损坏的文件

有时会出现编码的问题

 var result = new StreamWriter(output); 

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

您检查过文件是否确实没有损坏吗?

如果您使用的是ASP.NETMVC,为什么不从您的操作中返回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"); 
}

有几种方便的重载可以从字节[]或流或路径返回文件:

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