Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper wrap all values with quotes

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

like image 596
Ovi Avatar asked Jan 01 '19 13:01

Ovi


People also ask

What do the quotes around a field in a CSV file mean?

Quotes around a field in a CSV file are there for escaping text. When reading, if the field has quotes around the outside, they aren't a part of the field, and won't be a part of what the library returns to you, which is expected.

How to read a CSV file with csvhelper?

The type of data is IEnumerable<Person>. CsvHelper will automatically map each column to the property with the same name. For example, the value in FirstName column will be mapped into Person.FirstName. We can then iterate data and access the values in each row. The CsvConfiguration class has many configurables to control how we read a CSV file.

How to save as CSV file (UTF-8 with double quotes)?

Hello, you can change your file format to "CSV". You need to do the following: Select "Save as type", Click on the dropdown arrow to choose the new format, e.g., CSV file (UTF-8) Comma delimited. I hope the above instructions help you. Aug 03 2018 02:20 AM Aug 03 2018 02:20 AM Re: Save as CSV file (UTF-8) with double quotes - how?

What is the use of classmap in csvhelper?

The ClassMap comes to the rescue. Essentially, we subclass ClassMap and use it to tell CsvHelper which column should be mapped to which property.


2 Answers

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"
like image 186
Josh Close Avatar answered Oct 27 '22 19:10

Josh Close


From version 25.0.0 up to the date, the way of doing it is:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    ShouldQuote = args => true
};
like image 33
Nahue Gonzalez Avatar answered Oct 27 '22 21:10

Nahue Gonzalez