2013-12-17 35 views
0

我使用的TransmitFile和WriteFile寫一個Excel文件,但任何人都不能正常工作 我的代碼是:的TransmitFile和WriteFile不要工作

// Get the physical Path of the file(test.doc) 
     string filepath = newFilePath; 

     // Create New instance of FileInfo class to get the properties of the file being downloaded 
     FileInfo file = new FileInfo(filepath); 

     // Checking if file exists 
     if (file.Exists) 
     { 
      // Clear the content of the response 
      HttpContext.Current.Response.ClearContent(); 

      // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header 
      HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name)); 


      // Add the file size into the response header 
      HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); 

      // Set the ContentType 
      HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 

      // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead) 
      HttpContext.Current.Response.TransmitFile(file.FullName); 



     } 


     FileStream sourceFile = new FileStream(file.FullName, FileMode.Open); 
     float FileSize; 
     FileSize = sourceFile.Length; 
     byte[] getContent = new byte[(int)FileSize]; 
     sourceFile.Read(getContent, 0, (int)sourceFile.Length); 
     sourceFile.Close(); 
     HttpContext.Current.Response.ClearContent(); 
     HttpContext.Current.Response.ClearHeaders(); 
     HttpContext.Current.Response.Buffer = true; 
     HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 
     HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString()); 
     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
     HttpContext.Current.Response.BinaryWrite(getContent); 
+0

導致任何錯誤。發生了什麼錯誤? – iJade

+0

我沒有看到任何Excel文件的下載 –

+0

嘗試嘗試和趕上,看看你是否得到任何異常 – iJade

回答

0

我會把它簡化爲這個代替:

public ActionResult ExcelDoc(string newFilePath) 
{ 
    string filepath = newFilePath; 

    // Create New instance of FileInfo class to get the properties of the file being downloaded 
    FileInfo file = new FileInfo(filepath); 

    // Checking if file exists 
    if (file.Exists) 
    { 
     var fileBytes = System.IO.File.ReadAllBytes(filepath); 
     Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name)); 
     return File(new MemoryStream(fileBytes), "application/vnd.ms-excel"); 
    } 
    else 
    { 
     return Content("File does not exist"); 
    } 
} 
+0

我想在課堂上使用這段代碼,我必須返回什麼類型的文件? –

+0

我會讓這個類返回一個字節數組。這真是一個設計決定。 – hutchonoid