ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

Export C# list into CSV (Comma Separated Values) in ASP.NET CORE 3.0 Web Application

.Net .Net Core about 6 years ago || 10/27/2019 || 12.3 K View

  • Hide

Here we are going to build ASP.NET CORE 3.0 Web Application which will helps us to export C# list into CSV (Comma Separated Values).  Let’s get started by creating New .net core web application.

Now, add a new class called “ExportCSV.cs” inside controller folder. Open Add New Item Screen through Project name on Context Menu of Controller foder >> Add >> New Item >> Select Class.

Name it ExportCSV.cs.  

Click OK button.


Add following on ExportCSV implementation.

Write<T> (IList<T> list, bool includeHeader = true). 
  • To Creates and returns the generated CSV.  
Write<T> (IList<T> list, string fileName, bool includeHeader = true) 
  • Creates and returns the generated CSV and saves the generated CSV to the specified path. 
CreateCsvHeaderLine 
  • Creates CSV header line, if includeHeader is set true. 
CreateCsvLine<T>(T item, PropertyInfo[] properties). 
  • Creates a CSV line for the given type of the object. 
CreateCsvLine(IList<string> list). 
  • Creates a CSV line for the given list of the string by joining them, demarcated by comma.  
CreateCsvItem 
  • Adds the provided value item to the processed list, used to create CSV line. 
CreateCsvStringListItem 
  • Adds the provided string list as a single item to the processed list, which is used to create CSV line. 
CreateCsvStringArrayItem 
  • Adds the provided string array as a single item to the processed list, which is used to create CSV line. 
CreateCsvStringItem 
  • Adds the provided string value item to the processed list, used to create CSV line.  
ProcessStringEscapeSequence 
  • Processes the provided data to handle double quotes and comma value. If we do not apply escape sequences, they can corrupt the data.  
WriteFile 
  • Writes the generated CSV data to the file. 

Final  "ExportCSV.cs" file look like

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ExportListIntoCSV.Controllers
{
    public class ExportCSV
    {
        private const string DELIMITER = ",";
        public string Write<T>(IList<T> list, bool includeHeader = true)
        {
            StringBuilder sb = new StringBuilder();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();

            if (includeHeader)
            {
                sb.AppendLine(this.CreateCsvHeaderLine(properties));
            }

            foreach (var item in list)
            {
                sb.AppendLine(this.CreateCsvLine(item, properties));
            }

            return sb.ToString();
        }

        public string Write<T>(IList<T> list, string fileName, bool includeHeader = true)
        {
            string csv = this.Write(list, includeHeader);

            this.WriteFile(fileName, csv);

            return csv;
        }

        private string CreateCsvHeaderLine(PropertyInfo[] properties)
        {
            List<string> propertyValues = new List<string>();

            foreach (var prop in properties)
            {
                string stringformatString = string.Empty;
                string value = prop.Name;

                var attribute = prop.GetCustomAttribute(typeof(DisplayAttribute));
                if (attribute != null)
                {
                    value = (attribute as DisplayAttribute).Name;
                }

                this.CreateCsvStringItem(propertyValues, value);
            }

            return this.CreateCsvLine(propertyValues);
        }

        private string CreateCsvLine<T>(T item, PropertyInfo[] properties)
        {
            List<string> propertyValues = new List<string>();

            foreach (var prop in properties)
            {
                string stringformatString = string.Empty;
                object value = prop.GetValue(item, null);

                if (prop.PropertyType == typeof(string))
                {
                    this.CreateCsvStringItem(propertyValues, value);
                }
                else if (prop.PropertyType == typeof(string[]))
                {
                    this.CreateCsvStringArrayItem(propertyValues, value);
                }
                else if (prop.PropertyType == typeof(List<string>))
                {
                    this.CreateCsvStringListItem(propertyValues, value);
                }
                else
                {
                    this.CreateCsvItem(propertyValues, value);
                }
            }

            return this.CreateCsvLine(propertyValues);
        }
        private string CreateCsvLine(IList<string> list)
        {
            return string.Join(ExportCSV.DELIMITER, list);
        }
        private void CreateCsvItem(List<string> propertyValues, object value)
        {
            if (value != null)
            {
                propertyValues.Add(value.ToString());
            }
            else
            {
                propertyValues.Add(string.Empty);
            }
        }
        private void CreateCsvStringListItem(List<string> propertyValues, object value)
        {
            string formatString = "\"{0}\"";
            if (value != null)
            {
                value = this.CreateCsvLine((List<string>)value);
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));
            }
            else
            {
                propertyValues.Add(string.Empty);
            }
        }
        private void CreateCsvStringArrayItem(List<string> propertyValues, object value)
        {
            string formatString = "\"{0}\"";
            if (value != null)
            {
                value = this.CreateCsvLine(((string[])value).ToList());
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));
            }
            else
            {
                propertyValues.Add(string.Empty);
            }
        }
        private void CreateCsvStringItem(List<string> propertyValues, object value)
        {
            string formatString = "\"{0}\"";
            if (value != null)
            {
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));
            }
            else
            {
                propertyValues.Add(string.Empty);
            }
        }
        private string ProcessStringEscapeSequence(object value)
        {
            return value.ToString().Replace("\"", "\"\"");
        }
        public bool WriteFile(string fileName, string csv)
        {
            bool fileCreated = false;

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                File.WriteAllText(fileName, csv);

                fileCreated = true;
            }

            return fileCreated;
        }
    }
}

Now let’s Add Model Class “Employee.cs” with property EmployeeID, EmployeeName, Address in our project.

namespace ExportListIntoCSV.Models
{
    public class Employee
    {
        [Display(Name = "Employee ID")]
        public int EmployeeId
        {
            get;
            set;
        }
        [Display(Name = "Employee Name")]
        public string EmployeeName
        {
            get;
            set;
        }
        [Display(Name = "Address")]
        public string Address
        {
            get;
            set;
        }
    }
}

Now let’s create a list of type Employee in Index() of HomeController.cs

List<Employee> objEmployee = new List<Employee> {
            new Employee {
                EmployeeId = 1, EmployeeName = "RAM", Address="Kathmandu"
            },
            new Employee {
                EmployeeId = 2, EmployeeName = "Shyam", Address="Lalitpur"
            },
            new Employee {
                EmployeeId = 3, EmployeeName = "Raja", Address="Biratnagar"
            },
            new Employee {
                EmployeeId = 4, EmployeeName = "Sita", Address="Janakpur"
            },
            new Employee {
                EmployeeId = 5, EmployeeName = "Bhrikuti", Address="Birgunj"
            }
        };

Here our CSV will generated before returning Index view. so put following  

 string stringfileName = string.Format("{0}\\Final.csv", _environment.WebRootPath);
 ExportCSV objExportCSV = new ExportCSV();
 objExportCSV.Write(objEmployee, stringfileName, true);

_enviroment.WebRootPath is for hosting environment on path where we want to export our .CSV file. _enviroment is an object of IWebHostEnvironment. 

public static IWebHostEnvironment _environment;
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _environment = env;
        } 

Final "HomeController.cs" look like

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ExportListIntoCSV.Models;
using Microsoft.AspNetCore.Hosting;
namespace ExportListIntoCSV.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        public static IWebHostEnvironment _environment;
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _environment = env;
        }
        public IActionResult Index()
        {
            List<Employee> objEmployee = new List<Employee> {
            new Employee {
                EmployeeId = 1, EmployeeName = "RAM", Address="Kathmandu"
            },
            new Employee {
                EmployeeId = 2, EmployeeName = "Shyam", Address="Lalitpur"
            },
            new Employee {
                EmployeeId = 3, EmployeeName = "Raja", Address="Biratnagar"
            },
            new Employee {
                EmployeeId = 4, EmployeeName = "Sita", Address="Janakpur"
            },
            new Employee {
                EmployeeId = 5, EmployeeName = "Bhrikuti", Address="Birgunj"
            }
        };
            string stringfileName = string.Format("{0}\\Final.csv", _environment.WebRootPath);
            ExportCSV objExportCSV = new ExportCSV();
            objExportCSV.Write(objEmployee, stringfileName, true);
            return View();
        }
    }
}

Finally, after Running our project, we can see a generated Final.csv file inside wwwroot Folder.

Summary:

In this article, we learned how to Export C# list into CSV (Comma Separated Values) in ASP.NET CORE 3.0 Web Application .

  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Prakash Pokhrel

Prakash Pokhrel

https://np.linkedin.com/in/prakash-pokhrel-42a699a2

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey