Home > Blockchain >  CSVHelper insert currency value into file
CSVHelper insert currency value into file

Time:12-01

I have a decimal value that represents amount. I want to insert it into csv file like currency.

    await using var writer = new StreamWriter(csvPath);
    await using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.Context.RegisterClassMap<MyClass>();

        await csv.WriteRecordsAsync(data);
    };

In the map class I did

Map(x => x.Amount).Name("amount")
                .TypeConverterOption.NumberStyles(NumberStyles.Currency);

As a result I have just decimal value '141000' not like currency enter image description here Can I show in csv file decimal like currency?

CodePudding user response:

I believe TypeConverterOption.NumberStyles(NumberStyles.Currency) is only for converting a string to a number. If you want to go the other way, you will need to use TypeConverterOption.Format. I also found you can't use CultureInfo.InvariantCulture. You'll either need to use CultureInfo.CurrentCulture or the specific culture you need the currency symbol for.

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Amount = 141000 },
    };

    //using (var writer = new StreamWriter("path\\to\\file.csv"))
    using (var csv = new CsvWriter(Console.Out, CultureInfo.CurrentCulture))
    {
        csv.Context.RegisterClassMap<FooMap>();
        csv.WriteRecords(records);
    }
}

public class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        Map(m => m.Id);
        Map(m => m.Amount).Name("amount").TypeConverterOption.Format("C");
    }
}

public class Foo
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
}
  • Related