Ali
Ali

Reputation: 1235

Write CSV file with Upper Case Header

I am trying to write a csv file but with upper case headers. Entries is a collection of objects.

using (var streamWriter = new StreamWriter(csvStream))
            {
                var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
                {
                    PrepareHeaderForMatch = args => args.Header.ToUpper()
                };
                using (var csvWriter = new CsvWriter(streamWriter, csvConfig))
                {
                    csvWriter.WriteRecords<T>(entries);
                    streamWriter.Flush();
                }
           }

I can see the file has been written but headers are not in capital letter. What is wrong here?

Upvotes: 0

Views: 800

Answers (2)

David Specht
David Specht

Reputation: 9094

If you want a more generic approach to making all the headers uppercase, you can use the Map(Type classType, MemberInfo member, bool useExistingMap = true) overload of the Map method.

void Main()
{
    var records = new List<CsvModel>
    {
        new CsvModel { Name = "name", Family = "first" },
    };

    using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
    {
        var fooMap = new DefaultClassMap<CsvModel>();

        var properties = typeof(CsvModel).GetProperties();
        foreach (var property in properties)
        {
            fooMap.Map(typeof(CsvModel), property).Name(property.Name.ToUpper());
        }
        
        csv.Context.RegisterClassMap(fooMap);
        
        csv.WriteRecords(records);
    }
}

public class CsvModel
{
    public string Name { get; set; }
    public string Family { get; set; }
}

Upvotes: 0

sa-es-ir
sa-es-ir

Reputation: 5082

PrepareHeaderForMatch is for matching and mapping headers to your model when you want to Read a csv file not writing. for writing to csv file, you need to set Name attribute for your properties like this:

  public class CsvModel
    {
        [Name("NAME")]
        public string Name { get; set; }

        [Name("FAMILY")]
        public string Family { get; set; }
    }

Or you can set header names in csv mapping:

public class CsvModelMap : ClassMap<CsvModel>
{
    public CsvModelMap()
    {
        Map(m => m.Name).Index(0).Name("NAME");
        Map(m => m.Family).Index(1).Name("FAMILY");
    }
}

Upvotes: 1

Related Questions