I'm using CSVHelper and I don't know how to solve this.
Problem: I'm trying to read a CSV with numbers like '3,23E+11' but I have this error:
The conversion cannot be performed.
Text: '3,27E+11'
MemberType: System.Nullable`1[[System.Decimal, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
TypeConverter: 'CsvHelper.TypeConversion.NullableConverter'
I need to read it with comma values instead of dots.
I already tried change culture info
public IEnumerable<DTO> ReadFile(Task<Stream> file)
{
IEnumerable<DTO> records;
CultureInfo nfi = new CultureInfo("de-DE", false);
nfi.NumberFormat.NumberDecimalSeparator = ",";
using (var reader = new StreamReader(file.Result))
using (var csv = new CsvReader(reader, nfi))
try
{
csv.Configuration.PrepareHeaderForMatch = (header, index) => header.Trim();
csv.Configuration.TrimOptions = TrimOptions.Trim;
csv.Configuration.TypeConverterOptionsCache.GetOptions<decimal>().NumberStyle = NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign;
csv.Configuration.BadDataFound = null;
csv.Configuration.MissingFieldFound = null;
csv.Configuration.Delimiter = ";";
csv.Configuration.RegisterClassMap<CSVMapper>();
records = csv.GetRecords<DTO>().ToList();
}
catch (Exception e)
{
throw e;
}
return records;
}
I don't know if exists some way to parse the value in the cell using comma instead of dot :/
Thank you
You have setted the number configuration for decimal
, but by your exception your property type is nullable (decimal?
). Add the following line if you have any non-nullable decimal
property, or replace the existing one if you only have the nullable version (decimal?
) (notice the ?
in the code bellow)
csv.Configuration.TypeConverterOptionsCache.GetOptions<decimal?>().NumberStyle =
NumberStyles.Number | NumberStyles.AllowDecimalPoint |
NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign;