【问题标题】:CsvHelper not parsing empty column for doubleCsvHelper 不为双精度解析空列
【发布时间】:2020-09-03 13:28:57
【问题描述】:

我正在使用 CsvHelper 解析我的 CSV 文件。 在我的 CSV 中,我有一列包含双精度值,但 csv 生成工具可以将其创建为空字段。

CSV 示例

Name,Value,Date
Jim;1.23;20200901
John;;20200901

Jim 的 Value 字段可以正常工作,但是当它到达 John 的值为空时,我得到以下异常。

The conversion cannot be performed.
    Text: ''
    MemberType: System.Double
    TypeConverter: 'CsvHelper.TypeConversion.DoubleConverter'
An unexpected error occurred.

我在文档中找不到任何内容。我希望空字段默认为 0。

我的代码:

public class Transaction
{
    public string Name { get; set; }
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

在这种情况下,我像var result = ParseCsvZipArchiveEntry<Transaction>(zipArchiveEntry);一样运行下面的代码

private List<T> ParseCsvZipArchiveEntry<T>(ZipArchiveEntry zipArchiveEntry) where T : class
{
    string TempFilePath = Path.GetTempFileName();

    List<T> Result = null;

    try
    {
        zipArchiveEntry.ExtractToFile(TempFilePath, true);

        CsvHelper.Configuration.CsvConfiguration Config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
        Config.Delimiter = ";";

        using (var reader = new StreamReader(TempFilePath))
        using (var csv = new CsvReader(reader, Config))
        {
            Result = csv.GetRecords<T>().ToList();
        }
    }
    catch (Exception ex)
    {
        Logger(ex.Message);
    }
    finally
    {
        if(File.Exists(TempFilePath))
            File.Delete(TempFilePath);
    }

    return Result;
}

【问题讨论】:

    标签: c# .net csv csvhelper


    【解决方案1】:

    您可以将Default 属性应用于模型中的属性。它被宣传为The default value that will be used when reading when the CSV field is empty.

    using CsvHelper.Configuration.Attributes;
    
    public class Transaction
    {
        public string Name { get; set; }
        [Default(0)]  // set to 0 when the field is empty
        public double Value { get; set; }
        public DateTime Date { get; set; }
    }
    

    在我的测试中,这将返回 2 个事务实例的列表,其中第二个实例的 Value 为 0。

    该属性的 API 文档是 found here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多