CSVHelper FormatException与DateTime [英] CSVHelper FormatException with DateTime

查看:222
本文介绍了CSVHelper FormatException与DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题尤其是CSVHelper库.

The issue I have is with the CSVHelper library in particular.

我的csv文件看起来像这样:

My csv file looks something like this:

Number,Date,Account,Amount,Subcategory,Memo
 ,09/05/2017,XXX XXXXXX,-29.00,FT , [Sample string]
 ,09/05/2017,XXX XXXXXX,-20.00,FT ,[Sample string]
 ,08/05/2017,XXX XXXXXX,-6.30,PAYMENT,[Sample string]

我使用CSVHelper所做的事情是这样的:

What I am doing with CSVHelper is this:

        List<Transaction> result = new List<Transaction>();
        using (TextReader fileReader = File.OpenText("data.csv"))
        {
            var csv = new CsvReader(fileReader);
            result = csv.GetRecords<Transaction>().ToList();
        }

问题在于,当它尝试在最后一行执行GetRecord时,出现此异常:

The issue is that when It tries to execute GetRecord on the last line, I get this exception:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles)
   at CsvHelper.TypeConversion.DateTimeConverter.ConvertFromString(TypeConverterOptions options, String text)
   at lambda_method(Closure )
   at CsvHelper.CsvReader.CreateRecord[T]()
   at CsvHelper.CsvReader.<GetRecords>d__65`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

如您所见,数据存在一些问题-第一列为空或字符串为null.即便如此,异常消息仍指向日期(第二列)的问题.

As you can see the data has some issues - the first column is either empty or has the string null. Even then, the exception message points to a problem with the Date which is the second column.

任何帮助将不胜感激.

推荐答案

我的猜测是,您的默认区域性指定的日期格式与CSV文件中的日期格式不同.尝试将区域性设置为与数据相匹配的区域.

My guess is that your default culture specifies a different date format than what is in the CSV file. Try setting the culture to one that matches the data.

    var csv = new CsvReader(fileReader);
    csv.Configuration.CultureInfo = CultureInfo.GetCultureInfo("en-GB");
    result = csv.GetRecords<Transaction>().ToList();

提琴: https://dotnetfiddle.net/iTvc4Y

这篇关于CSVHelper FormatException与DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆