2014-01-21 61 views
0

我正在寫一個用於下載本地系統中的excel文件的代碼。詢問保存下載文件的位置

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); 
Microsoft.Office.Interop.Excel.Workbooks workBooks = excelApp.Workbooks; 
Microsoft.Office.Interop.Excel.Workbook workBook = workBooks.Open(@"D:\Myfile.xlsx"); 
// Microsoft.Office.Interop.Excel.Worksheet workSheet = workBook.Worksheets.get_Item(1); 

workBook.SaveCopyAs(@"D:\Copy_Myfile.xlsx"); 
workBook.Close(); 

現在的要求是,而不是將文件保存到D盤,它應該要求用戶將文件保存到desied位置。

有什麼想法?

+0

也許問他們一個文件瀏覽對話框? –

+0

你的意思是,用戶應該從服務器下載並保存到他的本地驅動器?像'Response.TransmitFile'一樣? – Taosique

回答

0
public static void TransmitFile(Page CurrentPage, string FilePath) 
// CurrentPage = this when called from CodeBehind 
{ 
    if (File.Exists(FilePath)) 
    { 
     string FileName = Path.GetFileName(FilePath); 
     string Extension = Path.GetExtension(FilePath).ToLowerInvariant(); 
     string ContentType; 

     switch (Extension) 
     { 
      case "xlsx": 
       ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       break; 
      case "xls": 
       ContentType = "application/vnd.ms-excel"; 
       break; 
      case "csv": 
       ContentType = "text/csv"; 
       break; 
      default: 
       ContentType = "application/octet-stream"; 
       break; 
     } 

     if (CurrentPage != null) 
     { 
      CurrentPage.Response.ContentType = ContentType; 
      CurrentPage.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName); 
      CurrentPage.Response.TransmitFile(FilePath); 
      CurrentPage.Response.End(); 
     } 
     else 
      throw new Exception("File transmission failed: cannot access current page"); 
    } 
    else 
     throw new Exception("File transmission failed: file not found"); 
}