Answers for "csvWriter.WriteRecords custom header"

0

csvWriter.WriteRecords custom header

using CsvHelper;
using System.Collections.Generic;
using System.IO;

namespace Test
{
    class Program
    {
        class CsvColumns
        {
            private string column_01;

            [CsvHelper.Configuration.Attributes.Name("Column 01")] // changes header/column name Column_01 to Column 01
            public string Column_01 { get => column_01; set => column_01 = value; }
        }

        static void Main(string[] args)
        {
            List<CsvColumns> csvOutput = new List<CsvColumns>();
            CsvColumns rows = new CsvColumns();
            rows.Column_01 = "data1";
            csvOutput.Add(rows);

            string filename = "test.csv";
            using (StreamWriter writer = File.CreateText(filename))
            {
                CsvWriter csv = new CsvWriter(writer);
                csv.WriteRecords(csvOutput);
            }
        }
    }
}
Posted by: Guest on July-02-2021
0

csvWriter.WriteRecords custom header

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvWriter(writer))
    {
        var records = new List<Person>
        {
            new Test { DisplayName = "one", Age = 1},
            new Test { DisplayName = "two", Age = 2 },
        };
        
        csv.Configuration.RegisterClassMap<PersonMap>();
        csv.WriteRecords(records);
        
        writer.Flush();
        stream.Position = 0;
        
        Console.WriteLine(reader.ReadToEnd());
    }
}

public class Person
{
    public string DisplayName { get; set; }
    public int Age { get; set; }
}

public sealed class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Map(m => m.DisplayName).Name("Display Name");
        Map(m => m.Age);
    }
}
Posted by: Guest on July-02-2021

Browse Popular Code Answers by Language