【发布时间】:2020-03-19 17:22:41
【问题描述】:
我目前正在使用 CSV 帮助程序来读取 csv 文件的内容并将其输出到控制台。我已经安装了 csvHelper nuget 包。但是,当我运行代码时,出现以下错误:
CsvHelper.TypeConversion.TypeConverterException: '无法执行转换。 文本: '' 会员类型: TypeConverter: 'CsvHelper.TypeConversion.Int32Converter''
我知道这是因为 csv 中的字段填充为空。我目前希望能够验证该字段并将其设置为 0。如何使用 CSVhelper 执行此操作。
我读取 csv 的代码是:
class ReaderCsv
{
private string _cvsfilepath;
public ReaderCsv(string csvfilepath)
{
this._cvsfilepath = csvfilepath;
}
public List <Country> ReadAllCountries()
{
var countries = new List<Country>();
using (var sr = new StreamReader(_cvsfilepath))
using (var csv = new CsvReader(sr, System.Globalization.CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = ",";
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
var country= new Country();
{
country.CountryName = csv.GetField("CountryName");
country.CountryCode = csv.GetField("CountryCode");
country.Continent = csv.GetField("CountryCode");
country.Population = csv.GetField<int>("Population");
}
countries.Add(country);
}
}return countries;
}
}
}
我的映射类是
public class CountryMap : ClassMap<Country>
{
public CountryMap()
{
Map(m => m.CountryName);
Map(m => m.CountryCode);
Map(m => m.Continent);
Map(m => m.Population);
}
}
【问题讨论】:
-
stackoverflow.com/questions/736629/parse-delimited-csv-in-net 它在 Visual Basic 命名空间中,但仍然有效。坏数据就是坏数据,你必须决定要么拒绝它,要么尝试解决它。
Rejection is protection我的一个朋友经常这么说。 -
嗨。如果我的建议解决了您的问题,您可以标记为答案吗?