Created
December 11, 2014 18:34
-
-
Save AlbertoMonteiro/671eddab7d61390a9d09 to your computer and use it in GitHub Desktop.
Customizando de forma flexível o nome das colunas usando CsvHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using CsvHelper; | |
| using CsvHelper.Configuration; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq.Expressions; | |
| using Xunit; | |
| namespace ClassLibrary1 | |
| { | |
| public class FluxoDeCaixa | |
| { | |
| public string Valor1 { get; set; } | |
| public string Valor2 { get; set; } | |
| } | |
| public class Teste | |
| { | |
| [Fact] | |
| public void TesteCsv() | |
| { | |
| var fluxos = new List<FluxoDeCaixa> { new FluxoDeCaixa { Valor1 = "1", Valor2 = "2" } }; | |
| string csv; | |
| using (var stringWriter = new StringWriter()) | |
| using (var csvWriter = new CsvWriter(stringWriter)) | |
| { | |
| var propCsvConfigurator = new PropCsvConfigurator<FluxoDeCaixa>(); | |
| propCsvConfigurator.MapeiaPropriedade("Valor1", "Valor10"); | |
| propCsvConfigurator.MapeiaPropriedade("Valor2", "Valor20"); | |
| csvWriter.Configuration.RegisterClassMap(propCsvConfigurator); | |
| csvWriter.WriteHeader<FluxoDeCaixa>(); | |
| csvWriter.WriteRecords(fluxos); | |
| csv = stringWriter.ToString(); | |
| } | |
| Assert.Equal(string.Format("Valor10,Valor20{0}1,2{0}", Environment.NewLine), csv); | |
| } | |
| } | |
| public class PropCsvConfigurator<T> : CsvClassMap<T> | |
| { | |
| public void MapeiaPropriedade(string propertyName, string newName) | |
| { | |
| var parameter = Expression.Parameter(typeof(T)); | |
| var expression = Expression.Lambda<Func<T, object>>(Expression.Property(parameter, propertyName), parameter); | |
| Map(expression).Name(newName); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment