阅读时如何忽略 CSV 中的空行

问题描述 投票:0回答:4

尝试使用

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 中的空白行,但事实并非如此。有什么想法吗?

c# csv csvhelper
4个回答
11
投票

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

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

8
投票

除了@David Specht 的回答。较新的版本更新了代表

ShouldSkipRecord
。我使用的是 28.0.1 版,下面的代码适用于我。

ShouldSkipRecord = args => args.Row.Parser.Record.All(string.IsNullOrWhiteSpace)

2
投票

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

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

1
投票

CsvHelper 23.0.0
中,另一种方法是管理读者异常

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

可以记录它、抛出它、绕过它并返回 false,甚至可以通过查看异常源来区分行为。

© www.soinside.com 2019 - 2024. All rights reserved.