C#Excel文件下载损坏文件?
我编写了一些代码,可以将某个文件下载到用户的计算机上,这是一个MS Excel.xlsx文件。问题是,当用户从我的web应用程序下载并打开文件时,我在excel中收到一条消息,“我们发现文件.xlsx中的某些内容有问题。”然后我单击“是”恢复内容,日志文件显示如下:C#Excel文件下载损坏文件?,c#,asp.net-mvc,excel,httpresponse,C#,Asp.net Mvc,Excel,Httpresponse,我编写了一些代码,可以将某个文件下载到用户的计算机上,这是一个MS Excel.xlsx文件。问题是,当用户从我的web应用程序下载并打开文件时,我在excel中收到一条消息,“我们发现文件.xlsx中的某些内容有问题。”然后我单击“是”恢复内容,日志文件显示如下: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <recoveryLog xmlns="http://schemas.openxmlformats.o
<?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>
有什么想法吗?您检查过文件是否确实没有损坏吗 如果您使用的是ASP.NETMVC,为什么不从您的操作返回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
有时是编码的问题
var result = new StreamWriter(output);
在写入输出缓冲流时不要使用任何特定的编码正如我所说,在文件资源管理器中,打开文件自然不会出错。一旦通过程序下载,文件就会出错。如果你能用FileResult告诉我怎么做,我可以把你的答案标记为正确。嘿,很抱歉回复得太晚了。我增强了答案,让我知道它是否有帮助。宾果对编码的评论。不要指定编码。
var result = new StreamWriter(output);