A.Pissicat A.Pissicat - 1 year ago 58
C# Question

Unable to create different columns in CSV

I try to create a csv file in c#. First I wrote a little piece of code to test. I saw on that post that the "," character is use to create different columns but it doesn't work for me.

I searched on different topic but all answer are something like

String.Format("{0},{1}", first, second);

My code :

String first = "Test name";
String second = "Value";
String newLine = String.Format("{0},{1}", first, second);
for (int i = 0; i < 3; i++)
first = "Test_" + i;
second = i.ToString();
newLine = String.Format("{0},{1}", first, second);
System.IO.File.WriteAllText(path, csv.ToString());

This create rightly the lines but all in column 1

Answer Source

Assuming csv to be a StringBuilder, this should create the file

Test name,Value

which is a valid CSV file with two columns and three rows (and headers).

Are you by any chance using a non-English locale (specifically, one that uses the comma as a decimal separator) and trying to load the CSV in Excel? In that case Excel assumes ; as the field separator instead of ,. You can split the data with custom settings if needed (I believe the feature is called “Text to fields”, or “Text to columns” on the Data tab in the ribbon).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download