How to create and download CSV files in ASP.NET MVC
Sometimes we have to create csv(comma separated) data files from our web applications and let the end user to download csv files. In ASP.NET MVC its not a much complicated issue. We can read whatever the data from a database, service or from another file and create a csv file.
In this post I’m going to explain how to create a .csv file from your existing data and let the end user download csv file with ASP.NET MVC.
For this I have created a new ASP.NET MVC project and added a new Action (“Downloads”) to the home controller to display the downloads page.
Then added a new view for the new Action. You can Right-click on the Downloads method and just click on the Add new View. Then add the new view with the same name as the action. Here I’m using the default layout as the layout for this page.
Next added a Link to download the csv file in View. Here is the view.
How the View looks like
Please note that I have added a css class to the link and also added an action method as a data attribute though we haven’t implemented that method yet. We can also use the href attribute instead of a data attribute.
Now in the Home controller I added a new action method for file download. Its a HttpGet method and the return type is FileContentResult. So we are promised to return a file from this method.
This method will extract the necessary data from your database and return the created csv file. For the file name I have added the time stamp so we can see the time which we downloaded the file. And for the data encoding I used the UTF8Encoding. If you have some special characters or unicode characters in data you have to use this kind of UTF encoding.
I have added a new Javascript file to my project and added the javascript code to call the action method in controller.
In this script we are reading the url from the link and call the controller method using Ajax.
When you add a new js file to your project, you have to register the file in the bundle config file. Please refer to this article to learn how to add custom scripts to a project.
And also you have to render the script into the page layout(“_Layout.cshtml”) as in the following screen. Then the scripts inside the custom js file will be loaded automatically into browser.
Make sure to register it after the jquery registration. Otherwise the jquery will give you some errors.
Now the methods and calling parts are done and we have to implement the data reading and file generating part.
In the controller implement the GenerateCSVString method to create the csv file.
private string GenerateCSVString() { var persons = GetPersonInfo(); StringBuilder sb = new StringBuilder(); sb.Append("Name"); sb.Append(","); sb.Append("Age"); sb.AppendLine(); foreach (var person in persons) { sb.Append(person.Name); sb.Append(","); sb.Append(person.Age); sb.AppendLine(); } return sb.ToString(); } private List<Person> GetPersonInfo()
{List<Person> persons = new List<Person>(); Person p1 = new Person() { Name = "Alex", Age = 23 }; Person p2 = new Person() { Name = "Jhon", Age = 26 }; persons.Add(p1); persons.Add(p2); return persons; }
For the data reading part I just used a hard coded data and you can read the data from the database.
Here is the full implementation for controller
using FileDownload.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace FileDownload.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Downloads()
{
return View();
}
[HttpGet]
public FileContentResult ExportList()
{
var csvString = GenerateCSVString();
var fileName = "PersonData " + DateTime.Now.ToString() + ".csv";
return File(new System.Text.UTF8Encoding().GetBytes(csvString), "text/csv", fileName);
}
private string GenerateCSVString()
{
var persons = GetPersonInfo();
StringBuilder sb = new StringBuilder();
sb.Append("Name");
sb.Append(",");
sb.Append("Age");
sb.AppendLine();
foreach (var person in persons)
{
sb.Append(person.Name);
sb.Append(",");
sb.Append(person.Age);
sb.AppendLine();
}
return sb.ToString();
}
private List<Person> GetPersonInfo()
{
List<Person> persons = new List<Person>();
Person p1 = new Person() { Name = "Alex", Age = 23 };
Person p2 = new Person() { Name = "Jhon", Age = 26 };
persons.Add(p1);
persons.Add(p2);
return persons;
}
}
}
Finally we have the working application…. To check the solution just click on the link and it will download csv file which contains comma separated values as we defined.
return File(new System.Text.UTF8Encoding().GetBytes(csvString), “text/csv”, fileName);
“File” is not found in my project
Set a debug point in that line and see whether the file has been created or not?