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

编程入门 行业动态 更新时间:2024-10-27 05:34:34
本文介绍了阅读时如何忽略CSV中的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Trying to read a CSV file that has empty rows (usually at the end) using CsvHelper.GetRecords<T>().

在没有空行的情况下,这种方法很有效.但是,如果CSV文件的行为空(定义为,,,,,),则会抛出TypeConverterException

Without the empty rows this works a treat. However if the CSV file has an empty row (defined as , , , , , ) then it throws a TypeConverterException

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

我已经阅读了文档( joshclose.github .io/CsvHelper/api/CsvHelper.Configuration/Configuration/),并尝试将配置对象设置为IgnoreBlankLines = true,但这没有用.

I have gone through the documentation (joshclose.github.io/CsvHelper/api/CsvHelper.Configuration/Configuration/) and have tried setting up the configuration object to IgnoreBlankLines = true however this has not worked.

简化为示例:

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通常包含以下内容:

The CSV would usually contain something like this:

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

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

I expected the IgnoreBlankLines to ignore the blank rows in the CSV but it is not. Any ideas?

推荐答案

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

you can try to implement ShouldSkipRecord on Configuration to choose skip or not

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

更多推荐

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

本文发布于:2023-05-25 10:58:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空行   CSV

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!