2016-05-30 79 views
0

創建新的Excel文件到客戶的電腦我有ASP.net MVC 5應用,我要在Excel如何在ASP.Net MVC

生成報告

目前我已經指定了一個路徑,但我想的是, excel應該被下載到不在路徑上的客戶端計算機上。

public void GenerateExcel() 
{ 
    Excel.Application application = new Excel.Application(); 
      Excel.Workbook workbook = application.Workbooks.Add(System.Reflection.Missing.Value); 
      Excel.Worksheet worksheet = workbook.ActiveSheet; 

      worksheet.Cells[1, 1] = "ID"; 
      worksheet.Cells[1, 2] = "Full Name"; 
      worksheet.Cells[1, 3] = "Position Title"; 
      worksheet.Cells[1, 4] = "Unit"; 
      worksheet.Cells[1, 5] = "Mobile"; 
      worksheet.Cells[1, 6] = "Email"; 
      worksheet.Cells[1, 7] = "Supervisor Email"; 
      worksheet.Cells[1, 8] = "Date and Time of Travel"; 
      worksheet.Cells[1, 9] = "Type of Trip"; 
      worksheet.Cells[1, 10] = "Distination"; 



      var query = from v in db.MyContextVR 
         join t in db.MyTripTypeContext on v.TypeOfTripId equals t.Id 
         select new VRsVM 
         { 
          Id = v.Id, 
          FullName = v.FullName, 
          PostitionTitle = v.PostitionTitle, 
          Unit = v.Unit, 
          Mobile = v.Mobile, 
          Email = v.Email, 
          SupervisorEmail = v.SupervisorEmail, 
          DateAndTimeOfTravel = v.DateAndTimeOfTravel, 
          TripName = t.TripName, 
          Distination = v.Distination 
         }; 


      int row = 2; 
      foreach (var item in query.ToList()) 
      { 
       worksheet.Cells[row, 1] = item.Id; 
       worksheet.Cells[row, 2] = item.FullName; 
       worksheet.Cells[row, 3] = item.PostitionTitle; 
       worksheet.Cells[row, 4] = item.Unit; 
       worksheet.Cells[row, 5] = item.Mobile; 
       worksheet.Cells[row, 6] = item.Email; 
       worksheet.Cells[row, 7] = item.SupervisorEmail; 
       worksheet.Cells[row, 8] = item.DateAndTimeOfTravel; 
       worksheet.Cells[row, 9] = item.TripName; 
       worksheet.Cells[row, 10] = item.Distination; 


       row++; 
      } 
      workbook.SaveAs("D:\\tempex/myreport.xlsx"); 

      workbook.Close(); 
} 

回答

0

您可以使用類似EPPlus輕鬆地創建存儲流中的Excel文件。之後,您可以使用content-disposition將其提供給客戶端(作爲下載)。

由科裏·阿德勒按照這個偉大的教程:
Easy Excel Interaction with EPPlus

+0

你有與ASP.Net MVC –

+0

檢查任何例如文件方法的重載答案中的一個 –

0

你有一對夫婦的這一個,當談到生成Excel文件選項,個人我已經使用免費的ClosedXml偉大成果圖書館,也可通過NuGet。我不會這麼想,因爲我覺得這不是問題的關鍵!

無論你的選擇,如果你想發送的Excel文件返回給客戶端的MVC中下載您將要第一次將文件保存到流,以獲得數據的文件生成庫的

using (System.IO.MemoryStream outputStream = new System.IO.MemoryStream()) 
{ 
    workbook.SaveAs(outputStream); 
    outputStream.Seek(0, SeekOrigin.Begin); 
    data = new byte[outputStream.Length]; 
    outputStream.Read(data, 0, (int)outputStream.Length); 
} 

然後,一旦你已經從模板中的數據,你可以從你的控制器操作中發回給用戶:

public ActionResult Download() { 
    byte[] data = GetExcel(); 
    return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Filename.xlsx") 
} 

編輯

另外還有一點需要一個流,那麼可以跳過其轉換爲一個字節數組,如果你已經有了一個流的文件