CsvHelper用引号将所有值括起来 [英] CsvHelper wrap all valus with quotes

查看:105
本文介绍了CsvHelper用引号将所有值括起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CsvHelper,我需要用引号将所有值包装起来. 有可能吗?

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

数据=是一个列表

 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();
            }

谢谢

推荐答案

有一个名为ShouldQuote的配置值,您可以在该值上在字段级别上确定是否应使用引号.

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; }
}

输出:

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

这篇关于CsvHelper用引号将所有值括起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆