Thursday, 16 January 2014

MVC 4: How do I download a list as a CSV?

I added a simple link in my view

@Html.ActionLink("Export Data", "ExportData")

and a simple method in my controller to take care of the download

public ActionResult ExportData()
return DownloadCSV();

public FileContentResult DownloadCSV()
string csv = string.Concat(from x in db.MyData
  select x.ID + ","
  + x.Name + "\n");

return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv",  string.Format("Export.{0}.csv", DateTime.Now.ToString("yyyy-MM-dd_HHmmss")));

No comments:

Post a comment