首页 > 解决方案 > CSV Helper 在分隔符后将字符串字段“名称”包装成双引号?

问题描述

我的文件中的 CSV 结果有一些问题,我已经用代码编写了下一个配置(我正在使用 CSVHelper 库)

public class ReportModelMap : ClassMap<ReportModel>
{
    public ReportModelMap()
    {
        Map(x => x.Name).Index(9).Name(" Name");
    }
}

客户需要在“名称”文本 =>“名称”之间添加空格。但是,该库将字符串包装成 'Name' 到双引号中,对我来说,这是错误的行为。我怎样才能使--Surname; 姓名——而不是——姓氏;“姓名”——

我在 CsvWriter 中找不到任何特定的配置来修复它

如果需要,我的保存逻辑

using (var writer = new StreamWriter(path))
using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
   csvWriter.Configuration.RegisterClassMap<ReportModelMap>();
   csvWriter.Configuration.Delimiter = ";";

   csvWriter.WriteRecords(ratingModels);
}

标签: c#.net-corecsvhelper

解决方案


@Panagiotis Kanavos 是正确的。您可以使用ShouldQuote仅覆盖该标题的引用行为。

void Main()
{
    var ratingModels = new List<ReportModel>
    {
        new ReportModel { Id = 1, Surname = "Surname", Name = " Name" } 
    };
    
    //using (var writer = new StreamWriter(path))
    using (var csvWriter = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
    {
        csvWriter.Configuration.RegisterClassMap<ReportModelMap>();
        csvWriter.Configuration.Delimiter = ";";
        csvWriter.Configuration.ShouldQuote = (field, context) => 
        {
            if (!context.HasHeaderBeenWritten && field == " Name") 
            {
                return false;
            } 
            else 
            {
                return ConfigurationFunctions.ShouldQuote(field, context); 
            }
        };

        csvWriter.WriteRecords(ratingModels);
    }
}

// You can define other methods, fields, classes and namespaces here
public class ReportModelMap : ClassMap<ReportModel>
{
    public ReportModelMap()
    {
        Map(x => x.Id).Index(0);
        Map(x => x.Surname).Index(1);
        Map(x => x.Name).Index(2).Name(" Name");
    }
}

public class ReportModel
{   
    public int Id { get; set; }
    public string Surname { get; set; }
    public string Name { get; set; }
}

推荐阅读