【问题标题】:CSVHelper FormatException with DateTimeCSVHelper FormatException 与 DateTime
【发布时间】:2017-05-10 08:54:19
【问题描述】:

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

我的 csv 文件如下所示:

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 做的是这样的:

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

问题是当它尝试在最后一行执行 GetRecord 时,我得到了这个异常:

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。即使这样,异常消息也指出第二列的日期有问题。

任何帮助将不胜感激。

【问题讨论】:

  • 你的 Transaction 类是什么样子的?也可能是默认情况下 CsvReader 希望使用与您在 CSV 文件中使用的日期格式不同的日期格式。

标签: c# csv csvhelper


【解决方案1】:

我的猜测是您的默认文化指定的日期格式与 CSV 文件中的不同。尝试将文化设置为与数据匹配的文化。

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

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

【讨论】:

  • 是的,就是这样。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 2016-09-09
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
相关资源
最近更新 更多