尝试使用 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 中的空白行,但事实并非如此。有任何想法吗?
最佳答案
@phat.huynh 有正确的想法。只需告诉它跳过所有字段都是空字符串的任何记录。
var configuration = new Configuration()
{
HasHeaderRecord = true,
HeaderValidated = null,
MissingFieldFound = null,
ShouldSkipRecord = record => record.Record.All(string.IsNullOrWhiteSpace)
};
关于c# - 阅读时如何忽略CSV中的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990749/