C#Excel文件下载破坏文件?

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

<?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。 另外,当我在文件夹资源pipe理器中打开文件时,问题不会出现, 只有下载后。 我已经尝试了谷歌浏览器和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(); 

有任何想法吗?

你有没有检查该文件实际上没有损坏?

如果您使用ASP .NET MVC,为什么不从您的操作中返回FileResult? 我会考虑这样做的标准方式。

更新你可以让你的控制器发送一个文件到浏览器下载,通过返回一个FileResult。 以与控制器内的View方法非常相似的方式使用File方法。

例:

 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或path返回文件有几个方便的重载:

 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 

有时候是编码问题

  var result = new StreamWriter(output); 

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