Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C#

How to Convert a List Object to CSV and Download? C# .NET

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
4 Jul 2017CPOL 58.6K   1   3
How to convert a List Object to CSV and download? C# .NET

Suppose you have a list of objects and wanted to generate CSV and download whenever the user clicks on the export button.

Create a button on with HTML .NET helper method.

UI Part

C#
@Html.ActionLink("Export Data","DownloadReport")

The first argument is a text you want to show to the user, the second one is the controller action name you are going to call that will generate and download the report of the list of objects of your choice.

Controller Action

Controller action would be something like this below:

C#
public FileResult DownloadReport()
{
    var lstData = new DataDbHandler().GetDetails();
    var sb = new StringBuilder();
    foreach (var data in lstData)
    {
        sb.AppendLine(data.Id+","+data.Name+",
        "+data.City+","+data.Country+","+data.Continent);
    }
    return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", "export.csv");
}

First, get the required list.
Second, create string builder object.
And go through from each of the items from the list, and append each data in separate line with comma separated.
And return file object, the first argument is content, second is the type of content and the third one is the name of the file you will see after download.

Ding dong, your download will be ready! ??

As simple is that, this action will create a CSV (Comma Separated Values) and start downloading with ease.

This is the easiest and simplest solution you will implement.

The post How to convert a List objects to CSV and download? C# .NET appeared first on ASIMplify.

License

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


Written By
Software Developer ASIMplify
Pakistan Pakistan
He is Khawaja Asim, A Microsoft Certified Professional, and Specialist. Software Engineer by profession, A Toastmaster, and a blogger. He loves to work on interesting projects.

https://asimplify.com

Comments and Discussions

 
Questionthanks! Pin
Member 148522223-Jun-20 3:27
Member 148522223-Jun-20 3:27 
SuggestionNice simple technique Pin
Member 109422615-Jul-17 3:58
Member 109422615-Jul-17 3:58 
QuestionA suggestion. Pin
George Swan4-Jul-17 22:22
mveGeorge Swan4-Jul-17 22:22 

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.