C#.NET:使用%转换器读取CSV

时间:2019-12-05 16:46:33

标签: c# filehelpers

我正在读取CSV文件

Name,Score
Pat,99%
Chris,87%

,并希望在通过FileHelpers读取文件时放弃百分号

using FileHelpers;

public class PctConverter : ConverterBase
{
    private NumberFormatInfo nfi = new NumberFormatInfo();

    public PctConverter()
    {
        nfi.PercentSymbol = "%";
    }

    public override object StringToField(string from)
    {
        return decimal.Parse(from, NumberStyles.Percent, nfi);
    }
}

[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
    public string Name { get; set; }
    public decimal Score { get; set; }
}

var student_file = "students.csv";
var engine = new FileHelperEngine<Student>();
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
List<Student> students = engine.ReadFileAsList(student_file);
ErrorInfo[] readingErrors = engine.ErrorManager.Errors;

但是我的转换器不太正确。你能建议为什么吗?

1 个答案:

答案 0 :(得分:-1)

您需要在要转换的字段上指定转换器,而且您的转换器对我不起作用,因此我对其进行了简化:

public class PctConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        return decimal.Parse(from.Replace("%", ""));
    }
}

[DelimitedRecord(",")]
[IgnoreFirst]
public class Student
{
    public string Name { get; set; }

    [FieldConverter(typeof(PctConverter))]
    public decimal Score { get; set; }
}