Search code examples
c#.netasp.net-core.net-coreexport-to-csv

How to Export CSV without using any Package in C# (,NET Core)?


How can you create a well structured csv file without using any packages in .NET core.

And use class Keys as Header.

    public class TestArray
    {
        public string LastName{ get; set; }
        public string FirstName { get; set; }
        public string Age { get; set; }
        public string MoNumber { get; set; }
    }

I tried with the CsvHelper Package, it's work Perfectly, but I want to Export csv file without using any packages.


Solution

  • public class TestArray
    {
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Age { get; set; }
        public string MoNumber { get; set; } 
    }
    
    public static void ExportCsv<TestArray>(List<TestArray> genericList, string filePath)
    {
        var sb = new StringBuilder();
        var header = "";
        var info = typeof(TestArray).GetProperties();
        if (!File.Exists(filePath))
        {
            var file = File.Create(filePath);
            file.Close();
            foreach (var prop in typeof(TestArray).GetProperties())
            {
                header += prop.Name + ",";
            }
            header = header.Substring(0, header.Length - 2);
            sb.AppendLine(header);
            TextWriter sw = new StreamWriter(filePath, true);
            sw.Write(sb.ToString());
            sw.Close();
        }
        foreach (var obj in genericList)
        {
            sb = new StringBuilder();
            var line = "";
            foreach (var prop in info)
            {
                line += prop.GetValue(obj, null) + ",";
            }
            line = line.Substring(0, line.Length - 2);
            sb.AppendLine(line);
            TextWriter sw = new StreamWriter(filePath, true);
            sw.Write(sb.ToString());
            sw.Close();
        }
    }
    

    Usage:

        var arrayData = new List<TestArray>
                        {
                            new() {
                                LastName = "John", FirstName = "Deo", Age = "20", MoNumber = "123456789"
                            },
                            new() {
                                LastName = "Seno", FirstName = "Verma", Age = "10", MoNumber = "9876543210"
                            }
                        };
    
        string filePath = "E:\\FolderName\\fileName.csv";  // file path should be include file Name and extention
    
        ExportCsv(arrayData, filePath);
    

    File Preview

    Downloaded File Preview