【问题标题】:How to ignore empty rows in CSV when reading读取时如何忽略 CSV 中的空行
【发布时间】:2019-09-18 10:34:04
【问题描述】:

尝试使用CsvHelper.GetRecords<T>() 读取包含空行(通常在末尾)的 CSV 文件。

没有空行,这是一种享受。但是,如果 CSV 文件有一个空行(定义为 , , , , , ),那么它会抛出 TypeConverterException

Text: ''
MemberType: IntelligentEditing.PerfectIt.Core.DataTypes.Styles.StyleRuleType
TypeConverter: 'CsvHelper.TypeConversion.EnumConverter'

我浏览了文档 (https://joshclose.github.io/CsvHelper/api/CsvHelper.Configuration/Configuration/) 并尝试将配置对象设置为 IgnoreBlankLines = true,但这没有奏效。

简化为一个例子:

public enum ItemTypeEnum
{
    Unknown = 0,
    Accounts = 1,
    HR = 2,
}


public class CsvItemDto
{
    public int Id { get; set; }

    public string Value { get; set; }

    public ItemTypeEnum ItemType { get; set; }
}

.
.
.
var configuration = new Configuration()
{
    HasHeaderRecord = true,
    HeaderValidated = null,
    MissingFieldFound = null,
    IgnoreBlankLines = true,

};
var csv = new CsvReader(textReader, configuration);
var rows = csv.GetRecords<CsvItemDto>();


if (rows != null)
{
    var items = rows.ToList();
    //Throws exception here
}

CSV 通常包含如下内容:

Id,Value,ItemType
1,This,Unknown
2,That,Accounts
3,Other,HR
,,
,,

我希望 IgnoreBlankLines 忽略 CSV 中的空白行,但事实并非如此。有什么想法吗?

【问题讨论】:

  • 这些只有点的行将被解释为第一列,即数字输入。无论您如何扭曲,对于一个裸整数列,这 非法输入。如果这些只是作为垂直的“...”省略号放在那里,请将它们排除在示例之外。
  • @Nyerguds 道歉我应该明确指出,这些点是我懒得输入的其他行。为了清楚起见,我会删除它们。干杯

标签: c# csv csvhelper


【解决方案1】:

@phat.huynh 有正确的想法。告诉它跳过所有字段都是空字符串的任何记录。

var configuration = new Configuration()
{
    HasHeaderRecord = true,
    HeaderValidated = null,
    MissingFieldFound = null,
    ShouldSkipRecord = record => record.Record.All(string.IsNullOrWhiteSpace)
};

【讨论】:

  • 我建议使用string.IsNullOrWhiteSpace(field),它将覆盖传入 CSV 流中可能存在的空字符以及其他不可见字符
【解决方案2】:

你可以尝试在 Configuration 上实现 ShouldSkipRecord 来选择是否跳过

var configuration = new Configuration () {
                HasHeaderRecord = true,
                HeaderValidated = null,
                MissingFieldFound = null,
                IgnoreBlankLines = true,
                ShouldSkipRecord = (records) =>
                {
                    // Implement logic here
                    return false;
                }
            };

【讨论】:

  • 我确实认为我只是假设这个问题是简单的配置布尔设置。如果没有其他答案出现,我可能会选择这个答案
【解决方案3】:

CsvHelper 23.0.0 中的另一种方法是管理阅读器异常

var conf = new CsvConfiguration(new CultureInfo("en-US"));
conf.ReadingExceptionOccurred = (exc) =>
{
    Console.WriteLine("Error");
    return false;
};

人们可以记录它、抛出它、绕过它返回错误甚至通过查看异常源来区分行为。

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2019-12-21
    相关资源
    最近更新 更多