2013-05-11 91 views
1

所有的美好的一天..我很新的ASP.net編程,所以請原諒我的示例代碼。我有一個擁有此操作碼的控制器。我想將Employee表中的數據放入CSV文件中。我不擅長linq查詢,所以我不知道如何按行排列。即時通訊使用MVC4。導出數據到CSV MVC4

public FileContentResult DownloadCSV() 
    { 

     //This is my linq query 
     var EmployeeQry = from data in db.Employees 
          select data; 

     //I want to put my Employee data into a CSV. something like this.. 
     string csv = "EmployeeName,EmployeePostion,EmployeeDepartment"; 
     return File(new System.Text.UTF8Encoding().GetBytes(csv),"text/csv","Report.csv"); 

    } 
+0

取看看這個庫:https://github.com/JoshClose/CsvHelper - 使它非常簡單。 – KorsG 2013-05-11 19:10:19

回答

1

試試這個:

string csv = string.Concat(
      EmployeeQry.Select(
        employee => string.Format("{0},{1},{2}\n", employee.Name, employee.Position, employee.Department))); 

或本(與替代語法相同):

string csv = string.Concat(from employee in EmployeeQry 
           select string.Format("{0},{1},{2}\n", employee.Name, employee.Position, employee.Department)); 
1

感謝馬蒂斯..但的String.Format沒有在LINQ工作。所以我在數據庫中進行了查詢並在本地格式化。

public FileContentResult DownloadCSV() 
{ 
    string csv = string.Concat(from employee in db.Employees 
           select employee.EmployeeCode + "," 
           + employee.EmployeeName + "," 
           + employee.Department + "," 
           + employee.Supervisor + "\n"); 
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report.csv"); 
} 
5

這工作一種享受,我(將需要適應您的特定需求)

在一個名爲DownloadController

控制器將這個
public void ExportToCSV() 
     { 
      StringWriter sw = new StringWriter(); 

      sw.WriteLine("\"First Name\",\"Last Name\",\"Email\",\"Organisation\",\"Department\",\"Job Title\""); 

      Response.ClearContent(); 
      Response.AddHeader("content-disposition", "attachment;filename=registereduser.csv"); 
      Response.ContentType = "application/octet-stream"; 

      ApplicationDbContext db = new ApplicationDbContext(); 

      var users = db.Users.ToList(); 

      foreach (var user in users) 
      { 
       sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\"", 

       user.FirstName, 
       user.LastName, 
       user.Email, 
       user.Organisation, 
       user.Department, 
       user.JobTitle 
       )); 
      } 
      Response.Write(sw.ToString()); 
      Response.End(); 

     } 

&呼叫使用

<a href="@Url.Action("ExportToCSV", "Download")">download the CSV of registered users</a>