How to convert C# List to CSV in ASP.NET Core


How to convert C# List to CSV in ASP.NET Core:


First Create an ASP.NET Core MVC Project :

Then:

Step 1: Create a Class in Model Folder:

using System.ComponentModel.DataAnnotations;
namespace ListToCSV.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;}
    }
}


Step 2: Create ExportCSV Class in Model Folder:
--===============================================================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ListToCSV.Models
{
    public class ExportCSV
    {
        private const string DELIMITER = ",";
        public string Write<T>(IList<T> list, string fileName, bool includeHeader = true)
        {
            string csv = this.Write(list, includeHeader);
            this.WriteFile(fileName, csv);
            return csv;
        }
        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();
        }
        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;
        }
    }
}


Step 3: Calling ExportCSV Class From Home Controller:  
--========================================================
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ListToCSV.Models;
using Microsoft.AspNetCore.Hosting;

namespace ListToCSV.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        List<Employee> objEmployee = new List<Employee> {
            new Employee { EmployeeId = 1, EmployeeName = "Rahul", Address="Dhaka"},
            new Employee { EmployeeId = 2, EmployeeName = "Sakib", Address="Dhaka"},
            new Employee { EmployeeId = 3, EmployeeName = "Sabbir", Address="Rajshahi"},
            new Employee { EmployeeId = 4, EmployeeName = "Karim", Address="Chittagong"},
            new Employee { EmployeeId = 5, EmployeeName = "Sumon", Address="Khulna"}
        };
        public static IWebHostEnvironment _environment;
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _environment = env;
        }
        public IActionResult Index()
        {
            string stringfileName = string.Format("{0}\\Final.csv", _environment.WebRootPath);
            ExportCSV objExportCSV = new ExportCSV();
            objExportCSV.Write(objEmployee, stringfileName, true);
            return View();
        }
     
    }
}

Post a Comment

0 Comments