Question

I am a beginner in C#, I am exporting some data to XL sheet in CSV format. My data contains a fullname column in which data is like (John, Delores "Sutton"). When I export this to XL it is dividing the data into two columns(or tabs) like Tab1: John and Tab2: Delores "Sutton" because of Comma(,). I want

If I use the below code

string F1 = base.GetColumnText(column, columnValue); //ex: John, Delores \"Sutton\""
string F2 = string.Format("\"{0}\"", F1); //ex: "\"John, Delores\"Sutton\"\""
streamWriter.Write(F2); //ex output in XL is: John, Delores Sutton""

The output in XL is:

John, Delores Sutton""

But I want it as :

John, Delores "Sutton"

Was it helpful?

Solution

You need to have double-double quotes to represent double quotes in a CSV, and everything must be surrounded by double quotes so your output in text will look like:

"John, Delores ""Sutton"""

So you will need to do a find and replace on the text to double your double quotes...

F1 = F1.Replace("\"", "\"\"");

Then do your format to surround text with quotes.

var F2 = string.Format("\"{0}\""), F1);

Savvy?

OTHER TIPS

Since commas are used to delimit fields, values with commas are interpreted as two fields. Such fields must be enclosed in quotes. As a result, fields that contain quotes must also be enclosed in quotes, and each quote within the field must be doubled up.

There are a number of rules for creating CSV files. I've written a very complete class for reading and writing CSV files and present the code in my article Reading and Writing CSV Files in C#. You might want to check that out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top