Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a csv file from List<String[]>

Tags:

c#

csv

linq

Can anyone help me to create a csv file from List, my scenario is, i have a multi dimensional values like below in a List

List<string[]> lst = new List<string[]>();
lst= csv1.ToList();

lst contains the values like,

lst[0] = {string[53]}
lst[1] = {string[53]}
lst[2] = {string[53]}
lst[3] = {string[53]}
lst[4] = {string[53]}

and string[53] contains the values like

lst[0]
    string[0] = "abc"
    string[1] = "def"
    string[2] = "ghi"
    string[3] = "jkl"
    string[4] = "mno"
    ...
lst[1]
    string[0] = "123"
    string[1] = "456"
    string[2] = "789"
    string[3] = "10"
    string[4] = "11"
    ...

I just wanted to write this multi-dimensional list to csv file as each item in lst[] to rows in csv and each item in string[] to columns such that the final output in my csv is

abc,def,ghi,jkl,mno
123,456,789,10,11

Any help would be really appreciated.

like image 206
Gnanasekaran Kuppusamy Avatar asked Dec 11 '12 07:12

Gnanasekaran Kuppusamy


People also ask

How do I save Comma Separated Values in CSV?

To save an Excel file as a comma-delimited file: From the menu bar, File → Save As. Next to “Format:”, click the drop-down menu and select “Comma Separated Values (CSV)” Click “Save”

How do you create a CSV file and write data in Java?

Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.

How do you put a comma in a string in CSV?

Re: Handling 'comma' in the data while writing to a CSV. So for data fields that contain a comma, you should just be able to wrap them in a double quote. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.


2 Answers

use linq:

File.WriteAllLines("text.txt", lst.Select(x => string.Join(",", x)));
like image 186
Jan Van Herck Avatar answered Oct 11 '22 08:10

Jan Van Herck


At the simplest level, not handling quoting / escaping / multi-line CSV issues, then just loop; maybe something like:

    using (var file = File.CreateText(path))
    {
        foreach(var arr in lst)
        {
           file.WriteLine(string.Join(",", arr));
        }
    }

or a tiny bit more efficient (no intermediary string):

    using (var file = File.CreateText(path))
    {
        foreach (var arr in lst)
        {
            if (String.IsNullOrEmpty(arr)) continue;
            file.Write(arr[0]);
            for(int i = 1 ; i < arr.Length ; i++)
            {
                file.Write(',');
                file.Write(arr[i]);
            }
            file.WriteLine();
        }
    }
like image 23
Marc Gravell Avatar answered Oct 11 '22 09:10

Marc Gravell