Click here to Skip to main content
15,885,278 members
Articles / General Programming / File
Article

Export To CSV file

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
11 Oct 2013CPOL2 min read 67.5K   4   2
First let’s see what the CSV file is:CSV file is a text based file in which data are separated by comma. It can be opened by excel so you can use

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

First let’s see what the CSV file is:

CSV file is a text based file in which data are separated by comma. It can be opened by excel so you can use excel functionality. Each row of data including the title is in separate line. Meanwhile, each row has data separated by comma.

 

How to create a CSV file?

We need to write data to the Response object. Meanwhile the content type should be text/csv also a header type of attachment should be added to response. Afterwards, column names are written to response then to actual data is written (each row should be just in one line).Finally you need to call Response.End to finalize your work.

Important: if any part of data has comma unfortunately the CSV file will screw up. What I did in the code is that I am replacing comma with space so I am sure that the only comma exists in each row is just for separating data rather than being part of data.

 

public class CSVExporter
{
    public static void WriteToCSV(List<Person> personList)
    {
        string attachment = "attachment; filename=PersonList.csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        WriteColumnName();
        foreach (Person person in personList)
        {
            WriteUserInfo(person);
        }
        HttpContext.Current.Response.End();
    }

    private static void WriteUserInfo(Person person)
    {
        StringBuilder stringBuilder = new StringBuilder();
        AddComma(person.Name, stringBuilder);
        AddComma(person.Family, stringBuilder);
        AddComma(person.Age.ToString(), stringBuilder);
        AddComma(string.Format("{0:C2}", person.Salary), stringBuilder);
        HttpContext.Current.Response.Write(stringBuilder.ToString());
        HttpContext.Current.Response.Write(Environment.NewLine);
    }

    private static void AddComma(string value, StringBuilder stringBuilder)
    {
        stringBuilder.Append(value.Replace(',', ' '));
        stringBuilder.Append(", ");
    }

    private static void WriteColumnName()
    {
        string columnNames = "Name, Family, Age, Salary";
        HttpContext.Current.Response.Write(columnNames);
        HttpContext.Current.Response.Write(Environment.NewLine);
    }

}

 
This article was originally posted at http://wiki.asp.net/page.aspx/401/export-to-csv-file

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
SuggestionFor Avoid Comma you could have use double quotes Pin
Vaibhav Agarwal18-May-17 1:18
Vaibhav Agarwal18-May-17 1:18 
Questionthanks, it was of great help. Pin
sarfraz779-Jun-14 4:59
sarfraz779-Jun-14 4:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.