CodeGo.net>如何处理与CsvHelper解析空列?
作者:互联网
我有一个CSV文件,我正在尝试解析它,但是在int数据类型列上收到以下错误.在该文件中,我正在为此列传递空白或空值.
[AutoMap(typeof(Test))]
[FileEntity("Test")]
public class TestFileEntity : BaseFileEntity
{
[CsvFileColumn(1)]
public int TestId { get; set; }
}
public IEnumerable<BaseFileEntity> Parse(Stream masterData, Type entityType, out IEnumerable<MasterDataFileParserError> errors)
{
var list = new List<BaseFileEntity>();
var errorList = new List<MasterDataFileParserError>();
try
{
using (var reader = new StreamReader(masterData))
{
var parser = new CsvReader(reader, new CsvHelper.Configuration.Configuration
{
HasHeaderRecord = true,
HeaderValidated = null,
MissingFieldFound = null
});
list.AddRange(parser.GetRecords(entityType).Cast<BaseFileEntity>());
}
}
catch (Exception ex)
{
if (ex.Data == null || ex.Data.Count == 0)
{
errorList.Add(new MasterDataFileParserError
{
Error = ex.Message,
Description = ex.ToString()
});
}
else
{
foreach (var key in ex.Data.Keys)
{
errorList.Add(new MasterDataFileParserError
{
Error = ex.Message,
Description = $"{key}: {ex.Data[key]}"
});
}
}
}
errors = errorList;
return list;
}
此行的异常:list.AddRange(parser.GetRecords(entityType).Cast< BaseFileEntity>());
错误:
An error has occurred while parsing ‘xyz.csv’ file for ‘Test’ entity:
‘[{“Error”:”The conversion cannot be performed.\r\n Text: ”\r\n
MemberType: System.Int32\r\n TypeConverter:
‘CsvHelper.TypeConversion.Int32Converter'”,”Description”:”CsvHelper.TypeConversion.TypeConverterException:
The conversion cannot be performed.\r\n Text: ”\r\n MemberType:
System.Int32\r\n TypeConverter:
‘CsvHelper.TypeConversion.Int32Converter’\r\n at
CsvHelper.Configuration.Configuration.<>c.<.ctor>b__148_4(CsvHelperException
exception)\r\n at
CsvHelper.CsvReader.d__65.MoveNext()\r\n at
System.Linq.Enumerable.d__341.MoveNext()\r\n at
1.AddEnumerable(IEnumerable
System.Collections.Generic.List1
1.InsertRange(Int32 index,
enumerable)\r\n at
System.Collections.Generic.List
IEnumerable1 collection)\r\n at
1& errors) in xyz.cs
Nec.Stanchion.Business.MasterDataFiles.Handling.MasterDataFileParser.Parse(Stream
masterData, Type entityType, IEnumerable
file”}]’.
原因很清楚,空白或空字符串与int数据类型不兼容,因此必须有某种方法允许int数据类型列值为空或null值.
CsvHelper版本= 6.0.0.0
解决方法:
我在当前项目中使用的是CsvHelper 6.1.0,只是测试了一个与您类似的用例,csv文件中的int字段为空白,并且没有问题.这是我正在使用的代码,希望对您有所帮助:
CsvReader csv = new CsvReader(new StreamReader(file.OpenReadStream()));
csv.Configuration.RegisterClassMap<PessoaCSVMap>();
csv.Configuration.Delimiter = ";";
csv.Configuration.HeaderValidated = null;
csv.Configuration.MissingFieldFound = null;
List<Pessoas> pessoas = csv.GetRecords<Pessoas>().ToList();
public sealed class PessoaCSVMap : ClassMap<Pessoas>
{
public PessoaCSVMap()
{
Map(m => m.Nome).Name("Nome", "Name");
... etc
}
}
标签:csvhelper,c 来源: https://codeday.me/bug/20191110/2013426.html