Download data as .CSV format from ASP.NET web application

CSV file is a comma separated file format. That means all the values in the file is comma separated. This is very simple and useful format to exchange data. You can create and read CSV very easily. It is in human readable as well as you can write your program logic to work with this format very easily. You need to place comma after every value in a line and at the time of reading also keep in mind. Many popular software and service also support CSV format. For example Microsoft Outlook, Gmail etc. Keep in mind that it is not hierarchical data rather it is tabular format which we can express in CSV format.

In this demo I am going to show you a sample code to create CSV file for your ASP.NET web application. If you have need to show your tabular data at your web page as well as download it in CSV format then this code will help you. I am using ASP.NET MVC for this demo purpose but you can also do this with ASP.NET WebForm.

So here I have a Model of Faculty. Also I have a simple repository to put and pull data from database.

public class Faculty
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Subject { get; set; }
    public DateTime JoiningDate { get; set; }
}
public class FacultyRepositary
{
    public List<Faculty> GetAll()
    {
        // Get all faculty data.
    }

    public void Insert(IList<Faculty> facs)
    {
        // Insert new faculty data.
    }

    // Other dal related methods...
}

Now suppose I have a Faculty controller. This has three action methods. One to show all data in our web page, one to insert new data and one to download all data in CSV format. To make this as simple as possible I am trying to post the code as relevant as possible.

public class FacultyController : Controller
{
    //
    // GET: /Faculty/

    public ActionResult Index()
    {
        IList<Faculty> faculties = new FacultyRepositary().GetAll();
        return View(faculties);
    }

    public void Insert()
    {
        // Insert new faculty data using repository.
    }

    public void DownloadCsv()
    {
        IList<Faculty> faculties = new FacultyRepositary().GetAll();
        string facsCsv = GetCsvString(faculties);
        
        // Return the file content with response body. 
        Response.ContentType = "text/csv";
        Response.AddHeader("Content-Disposition", "attachment;filename=Faculties.csv");
        Response.Write(facsCsv);
        Response.End();
    }

    private string GetCsvString(IList<Faculty> faculties)
    {
        StringBuilder csv = new StringBuilder();

        csv.AppendLine("FirstName,MiddleName,LastName,Subject,JoiningDate");

        foreach (Faculty faculty in faculties)
        {
            csv.Append(faculty.FirstName + ",");
            csv.Append(faculty.MiddleName + ",");
            csv.Append(faculty.LastName + ",");
            csv.Append(faculty.Subject + ",");
            csv.Append(faculty.JoiningDate.ToShortDateString());

            csv.AppendLine();
        }

        return csv.ToString();
    }
}

The idea is to format and put all the data inside a string and then return in the response body. Also we have to set the proper Response header for this. Also we have a view in which we have a link to this method.

@model IEnumerable<MvcApplication5.Models.Faculty>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MiddleName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Subject)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.JoiningDate)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MiddleName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Subject)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.JoiningDate)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
    }

</table>

<br />
<br />

<!-- Download data as CSV format. -->
<a href="/Faculty/DownloadCsv">Download CSV</a>
FirstName,MiddleName,LastName,Subject,JoiningDate
demo fac 1,Kumar,Roy,C#,15/09/2013
demo fac 2,Kumar,Roy,VB,16/09/2013

After running in the browser if we click on that link to download the CSV then we can see the browser will give option to download and save the file in your local computer. Then you can open it using notepad to see the content. Also note Microsoft Excel can open CSV file in to tabular format. So after downloading you can open it using Microsoft Excel or Open Office Calc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s