First of all, I would like to remind you that mounting a CSV correctly is not as simple as it seems, so I advise you to use the CsvHelper
as for Displayname, you can check if Property has this attribute using the method PropertyIjnfo.GetCustomAttribute<T>
. Follow 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 make use of the method PropertyInfo.GetCustomAttributes
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 the CsvHelper
.:
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")
}
can show the code you are using to generate csv?
– Ricardo Pontual
can yes. I will post below
– Ricardo Soares
@Ricardosoares edit the question with the code.
– CypherPotato