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

How to ignore empty rows in CSV when reading

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

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

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

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

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

CsvHelper 23.0.0 中的另一种方法是管理 reader 异常

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

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