First of all, I'd like to remind you that putting up a CSV correctly is not as simple as it sounds, so I advise you to use % with_% / a>
Regarding the DisplayName, you can verify that Property has this attribute by using the CsvHelper
". Here is an example:
public class Exemplo
{
[Display(Name = "Property 01")]
public string Prop1 { get; set; }
[Display(Name = "Property 02")]
public string Prop2 { get; set; }
[Display(Name = "Property 02")]
public string Prop3 { get; set; }
}
var props = typeof(Exemplo).GetProperties().Select(prop => {
var display = prop.GetCustomAttribute<DisplayAttribute>();
if (display != null)
return display.Name;
return prop.Name;
});
Console.WriteLine(String.Join(", ", props));
Depending on your version of .NET, you may need to use the PropertyIjnfo.GetCustomAttribute<T>
var props = typeof(Exemplo).GetProperties().Select(prop => {
var attributes = prop.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Length > 0) {
var display = attributes[0] as DisplayAttribute;
return display.Name;
}
return prop.Name
});
Console.WriteLine(String.Join(", ", props));
Follow the example using PropertyInfo.GetCustomAttributes
.:
public class Exemplo
{
[Display(Name = "Property 01")]
public Guid Prop1 { get; set; }
[Display(Name = "Property 02")]
public Guid Prop2 { get; set; }
[Display(Name = "Property 03")]
public Guid Prop3 { get; set; }
}
public class ExemploMap : ClassMap<Exemplo>
{
public ExemploMap()
{
var type = typeof(Exemplo);
var props = type.GetProperties();
foreach (var prop in props)
{
var display = prop.GetCustomAttribute<DisplayAttribute>();
Map(type, prop).Name(display?.Name ?? prop.Name);
}
}
}
var itens = Enumerable.Range(0, 11).Select(i => new Exemplo
{
Prop1 = Guid.NewGuid(),
Prop2 = Guid.NewGuid(),
Prop3 = Guid.NewGuid(),
});
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream, Encoding.UTF8, Int16.MaxValue, true))
{
var csvWriter = new CsvHelper.CsvWriter(writer);
csvWriter.Configuration.RegisterClassMap<ExemploMap>();
csvWriter.Configuration.Delimiter = ";";
csvWriter.WriteRecords(itens);
csvWriter.Flush();
}
File(stream, "text/csv", "consulta.csv")
}