0

I'm having trouble saving a 2D array string[,] to a csv file in C#. I want each element to be in its own cell when I open the .csv file in Excel but with this code everything ends up in one column. What should I change in order to have every element in its own cell?

public static void Main(string[] args) { string[,] array = new string[2, 5]; array[0, 0] = "ID"; array[0, 1] = "Turns"; array[0, 2] = "Forward Results"; array[0, 3] = "Backward Results"; array[0, 4] = "Trainings"; array[1, 0] = "SEL-HYS-001"; array[1, 1] = "5"; array[1, 2] = "100%"; array[1, 3] = "100%"; array[1, 4] = "1"; StreamWriter sw = File.CreateText("outputText.csv"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 5; j++) { sw.Write(array[i, j] + ";"); } sw.Write("\n"); } sw.Flush(); sw.Close(); Console.WriteLine("Success!"); } 
3
  • 1
    You are separating values with a semi-colon, but the csv format uses commas as delimiter, that's why it's not working as you expect it. Commented Nov 29, 2020 at 22:22
  • @nick Ok I am glad it was that easy of a fix, thank you so much! Commented Nov 29, 2020 at 22:24
  • The field separator in Excel for loading CSV files depends on the language. A german Excel has a semicolon ";" as a field separator. Commented Nov 29, 2020 at 22:27

1 Answer 1

1

Let's split the initial problem in two; first, convert string[,] data into csv:

using System.IO; using System.Linq; ... private static IEnumerable<string> ToCsv(string[,] data, char delimiter = ';') { for (int r = 0; r < data.GetLength(0); ++r) { StringBuilder sb = new StringBuilder(); for (int c = 0; c < data.GetLength(1); ++c) { string v = data[r, c] ?? ""; // Do we have to escape? E.g. abc;d"ef -> "abc;d""ef" if (v.Any(c => c < ' ' || c == '"' || c == delimiter)) v = "\"" + v.Replace("\"", "\"\"") + "\""; if (sb.Length > 0) sb.Append(delimiter); sb.Append(v); } yield return sb.ToString(); } } 

Then write the data into a file:

string[,] array = ... File.WriteAllLines("outputText.csv", ToCsv(array)); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.