CsvHelper wrap all valus with quotes

假装没事ソ 提交于 2020-07-03 03:20:10

问题


I am using CsvHelper I need to wrap all values with quotes. Is that possible?

Data = is a List

 using (StreamWriter textWriter = new StreamWriter(path))
            {
                textWriter.BaseStream.Write(p, 0, p.Length);
                // var dt = new DataTable();
                var csv = new CsvWriter(textWriter);
                csv.WriteRecords(Data);
                textWriter.Flush();
                textWriter.Close();
            }

Thanks


回答1:


There is a config value called ShouldQuote where you can determine on a field level if it should be quoted.

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Name = "one" },
        new Foo { Id = 2, Name = "two" },
    };

    using (var writer = new StringWriter())
    using (var csv = new CsvWriter(writer))
    {
        csv.Configuration.ShouldQuote = (field, context) => true;
        csv.WriteRecords(records);

        writer.ToString().Dump();
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Output:

"Id","Name"
"1","one"
"2","two"



回答2:


Just need to add a configuration object. like this

CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
               config.QuoteAllFields = true;
                var csv = new CsvWriter(textWriter, config);


来源:https://stackoverflow.com/questions/53995909/csvhelper-wrap-all-valus-with-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!