How to write a value which contain comma to a CSV file in c#?

user1027129 picture user1027129 · Nov 11, 2011 · Viewed 47.7k times · Source

I am using a data table for storing data.

I am exporting the data from data table to CSV file.

Sometimes there may be values containing comma(,) so the values are not exported correctly.

For Example

Consider the value is "9,11,32". I have to export as such.

But when I do the first column conatins 9 then in next column 11.

I want to display 9,11,32 in the same column in the CSV file. How do I do that?

Answer

Anh Hoang picture Anh Hoang · Mar 27, 2015

Simply put your data inside the backslash like this: "\"" + yourdata + "\"". Take a look on the example below:

StringWriter csv = new StringWriter();
// Generate header of the CSV file
csv.WriteLine(string.Format("{0},{1}", "Header 1", "Header 2"));
// Generate content of the CSV file
foreach (var item in YourListData)
{
    csv.WriteLine(string.Format("{0},{1}", item.Data1, "\"" + item.Data2 + "\""));
}

return File(new System.Text.UTF8Encoding().GetBytes(csv.ToString()), "application/csv", string.Format("{0}{1}", "YourFileName", ".csv"));

In the example: Your data2 may contains comma ","