2013-05-11 4 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

답변

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

감사 Matis ..하지만 및 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>