getcsv_example

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
					
public class Program
{
	public static void Main()
	{
		string[] columns = { "col1", "col2", "col3" };
		List<object[]> data = new List<object[]>();
		data.Add(new object[] {"row1", 1, 5 } );
		data.Add(new object[] {"row2", 2, 5 } );

		data.Add(new object[] {"row3", 3, 5 } );

		data.Add(new object[] {"row4", 4, 5 } );

		Console.WriteLine(GetCsv(columns, data));
		
	}
	
public static string GetCsv(string[] columns, List<object[]> data)
{
    StringBuilder CsvData = new StringBuilder();

    //add column headers
    string[] s = new string[columns.Length];
    for (Int32 j = 0; j < columns.Length; j++)
    {
        s[j] = columns[j];
        if (s[j].Contains("\"")) //replace " with ""
            s[j].Replace("\"", "\"\"");
        if (s[j].Contains("\"") || s[j].Contains(" ")) //add "'s around any string with space or "
            s[j] = "\"" + s[j] + "\"";
    }
    CsvData.AppendLine(string.Join(",", s));

    //add rows
    foreach (var row in data)
    {
        for (int j = 0; j < columns.Length; j++)
        {
            s[j] = row[j] == null ? "" : row[j].ToString();
            if (s[j].Contains("\"")) //replace " with ""
                s[j].Replace("\"", "\"\"");
            if (s[j].Contains("\"") || s[j].Contains(" ")) //add "'s around any string with space or "
                s[j] = "\"" + s[j] + "\"";
        }
        CsvData.AppendLine(string.Join(",", s));
    }

    return CsvData.ToString();

}
}
;