2012-08-16 27 views
0

我在頁面上顯示一個包含數據的表格,然後當用戶單擊「導出」時,我將數據放入Excel文件中。現在我想打開這個文件,以便用戶可以保存它或只是查看它。這是我的代碼。它提示用戶保存文件,但該文件是整個頁面!這裏有什麼不對?ASP.NET MVC在點擊按鈕時打開Excel文件

string filename = filePath.Substring(12); 
         System.IO.File.Copy(filePath, "C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename, true); 
         Response.Clear(); 
         Response.ContentType = @"application\xls"; 
         // FileInfo file = new FileInfo(Server.MapPath("~/Content/" + filename)); 
         Response.AddHeader("Filename", filename); 
         Response.ContentType = "application/xls"; 
         Response.TransmitFile("C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename); 
         //Response.WriteFile(file.FullName); 
         Response.Flush(); 

回答

2

使用File方法(返回FileResult)。您不應該在MVC應用程序中直接使用Response

public ActionResult YourAction() 
{ 
    ... 
    string filename = filePath.Substring(12); 
    return File(Path.Combine(@"C:\Work\MCTestSuiteCertificate\TS.ToDoViewer\Content", filename), "application/xls"); 
} 

PS還請注意使用Path.Combine而不是字符串連接。

+0

謝謝。這很好用! – Tulips 2012-08-16 13:01:06

+0

@Serg當我這樣做時,我沒有錯誤 - 但是excel也沒有打開。我把它稱爲: ** ** – ManInMoon 2017-01-10 12:30:53

+0

Check客戶端和服務器之間的HTTP調用以找出問題所在。 – 2017-01-16 11:54:00