2014-10-19 98 views
0

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

<?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的正确模式。另外,当我在文件夹资源管理器中打开该文件时,仅在下载后才会出现该问题,我已经尝试了谷歌浏览器和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(); 

任何想法?

回答

1

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

如果您使用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"); 
} 

有几种便利重载从字节[]返回一个文件或流或路径:

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 
+0

正如我所说,在文件资源管理器中,打开文件自然不会给出任何错误。一旦通过程序下载,该文件就有错误。如果你可以用FileResult显示我的方式,我可以将你的答案标记为正确的? – 2014-10-19 13:06:41

+0

嘿,对不起,迟交回复。我增强了答案,让我知道它是否有帮助。 – Mzn 2014-10-23 05:26:04

1

有时它是编码的问题

var result = new StreamWriter(output); 

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