Asim

This is Asim, a full stack web developer, a Toastmaster, and Ninja too. Passionate about building and learning new technologies. Any problem? wanna fight? then write your anger at: me@asimplify.com +(92)345 5306849

Categories
Tags

How to convert a List objects to CSV and download? C# .Net

How to convert a List objects 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

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

The first argument is a text you want to show that to the user, the second one is the controller action name you will 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:

        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.

Comments

comments

Asim
asimaslam.kh@gmail.com
Please wait...

Have courage to interact?

Any problem? Wanna fight? Get yourself subscribe first.