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.
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?
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 ","