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

时间:2019-09-18 10:34:04

标签: c# csv csvhelper

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

3 个答案:

答案 0 :(得分:1)

@ phat.huynh有一个正确的主意。只是告诉它跳过所有字段均为空字符串的任何记录。

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

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

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

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