c# - 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);
}
解决方案
@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; }
}
推荐阅读
- reactjs - 类型错误:images.map 不是函数
- java - 未定义类型 SecurityConfiguration 的方法 withDefaults()
- android-studio - Flutter show download failed with java.lang.IllegalArgumentException after download 100%
- mysql - LIMIT 从带有 JOIN 的 SELECT 语句返回不正确的结果(在 mySQL 中)
- javascript - 将多维数组插入多维数组 - Javascript
- windows - 运行 PostgreSQL 的 psql 命令时出错
- c++ - 如何在某个地址创建对数组的引用?
- python - 无法通过 Python ncclient 访问 Yang 功能
- javascript - 我的 kick 命令让服务器中的任何人都可以踢某人
- python - Django 使用 FTP 处理大文件