2013-03-15 54 views
1

我已經寫了一個excel的interop代碼來生成Excel表格報告。生成報告並保存在一個文件夾中。在此之後,我想下載相同的文件,並且我已經在同一個應用程序中編寫了一個代碼供下載。文件格式是.xlsx。下載時出現以下錯誤。下載Excel中的excel文件#

Cannot open the file, file fotmat may be different or file may be corrected. 

但是,如果我直接去驅動器,我可以打開相同的文件。

下載代碼

private void DownloadFile(string getpathfromappconfig, string FileName) 
{ 
    string path = @getpathfromappconfig + "\\" + FileName + ".xlsx"; 
    System.IO.FileInfo file = new System.IO.FileInfo(path); 
    string Outgoingfile = FileName + ".xlsx"; 
    if (file.Exists) 
    { 
     Response.Clear(); 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile); 
     Response.AddHeader("Content-Length", file.Length.ToString()); 
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
     Response.WriteFile(file.FullName); 

    } 
    else 
    { 
     Response.Write("This file does not exist."); 
    } 

} 

有人可以幫我解決這個問題?

+0

哪些ASP.Net框架,您使用的嘗試? WebForms或MVC? – Aron 2013-03-15 10:35:02

+0

我正在使用框架3.5。 – Sanju 2013-03-15 10:37:59

+0

是這個內容類型被添加到你的iis內容類型列表 – JSJ 2013-03-15 10:38:51

回答

2

您可以使用此代碼

Response.ContentType = "application/vnd.ms-excel" 

嘗試替換此

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 

或者你可以用這個代碼

  Excel.Application xlApp ; 
      Excel.Workbook xlWorkBook ; 
      Excel.Worksheet xlWorkSheet ; 
      object misValue = System.Reflection.Missing.Value; 

      xlApp = new Excel.ApplicationClass(); 
      xlWorkBook = xlApp.Workbooks.Open("YourFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); 
      xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 


      //your treatment ... 

      xlWorkBook.Close(true, misValue, misValue); 
      xlApp.Quit(); 

      //Clean your objects 
+0

我嘗試了兩個。打開時同樣的格式錯誤。 – Sanju 2013-03-15 10:39:29

+0

這是供下載嗎? – Sanju 2013-03-15 10:44:26

+0

是的,你可以使用下載 – 2013-03-15 10:45:09