2014-10-19 96 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); 

寫入輸出緩衝流時不要使用任何特定的編碼