2013-08-30 48 views
1

我將我的jQuery DataTable更改爲服務器端實現,它工作正常。現在我想添加下載XLS的功能;類似於非服務器端表中內置的csv導出。我有一些與此類似:服務器端DataTable在ASP.NET中的XLS下載應用

$(document).ready(function() { 
    $('#example').dataTable({ 
     "sDom": 'T<"clear">lfrtip', 
     "oTableTools": { 
      "aButtons": [ { 
       "sExtends": "download", 
       "sButtonText": "Download XLS", 
       "sUrl": "/generate_xls.php" 
      } ] 
     } 
    }); 

問題:

  1. 如何下載我的.NET應用程序的文件,而不必使用PHP?

  2. 如何獲取我的xls或csv文件的所有表格數據?顯然它們位於服務器上,因此它不像我最初的前端實現那樣直截了當。

隨時提供任何有用的鏈接或指針!謝謝!

回答

0

好吧,我能弄明白我自己(在另一個答案的幫助下)。基本上我將「sURL」設置爲指向控制器動作,然後該控制器創建並下載如下的CSV文件:

public ActionResult AccountsExportCSV() 
    { 
     MemoryStream output = new MemoryStream(); 
     StreamWriter writer = new StreamWriter(output); 
     load_repo(); 
     var accounts = _repo.GetAllAccounts(); 

     writer.Write("Email"); 
     writer.Write(","); 
     writer.Write("Full Name"); 
     writer.Write(","); 
     writer.Write("Phone"); 
     writer.Write(","); 
     writer.Write("Points"); 
     writer.Write(","); 
     writer.Write("Date Added"); 
     writer.Write(","); 
     writer.Write("Last Sync"); 
     writer.Write(","); 
     writer.Write("User Type"); 
     writer.WriteLine(); 

     int userType = 0; 

     foreach (Account account in accounts) 
     { 
      writer.Write(account.Email); 
      writer.Write(","); 
      writer.Write(account.FullName); 
      writer.Write(","); 
      writer.Write(account.Phone); 
      writer.Write(","); 
      writer.Write(account.Points); 
      writer.Write(","); 
      writer.Write(account.AddDate); 
      writer.Write(","); 
      writer.Write(account.LastDate); 
      writer.Write(","); 
      userType = Convert.ToInt32(account.UserType); 
      switch (userType) 
      { 
       case 0: 
        writer.Write("Unknown"); 
        break; 
       case 1: 
        writer.Write("User"); 
        break; 
       case 10: 
        writer.Write("Support"); 
        break; 
       case 20: 
        writer.Write("Manager"); 
        break; 
       case 30: 
        writer.Write("Admin"); 
        break; 
       case 40: 
        writer.Write("Developer"); 
        break; 
      } 
      writer.WriteLine(); 
     } 

     writer.Flush(); 
     output.Position = 0; 

     return File(output, "text/comma-seperated-values", "accounts.csv"); 
    } 
相關問題