Search code examples
c#excelwinformsarraylistexport-to-csv

How to export excel from List<string> C#?


I have the list with content look like that

"Food"<|||>"Candy"<|||>"15"
"System"<|||>"IOS, Android"<|||>"2023"
"Fruit"<|||>"Apple,Orange "<|||>"100"
"Wine"<|||>"Whisky"<|||>"250"

I try specific character <|||> , which will be define separated to excel format . The excel result will have 3 columns .

enter image description here

but i don't know it can be do, this looks difficult because excel will only identify on commas, not sure if it can use special characters, and inside the cell content, we also have commas.

var lines = new List<string>();
lines.AddRange("Food"<|||>"Candy"<|||>"15","System"<|||>"IOS, Android"<|||>"2023","Fruit"<|||>"Apple,Orange "<|||>"100","Wine"<|||>"Whisky"<|||>"250");
//export to excel 

Solution

  • Since the last column of your excel file contains an integer then you can use a conditional structure to check if the array member at the current index contains a number using Int32.TryParse() then you append that item and a line break to the csv else append the item and a comma like in the code below.

    var array = new string[]
    {
        "Food","Candy","15",
        "System","IOS, Android","2023",
        "Fruit","Apple, Orange","100",
        "Wine","Whisky","250"
    };
    //create a new list to hold the items
    var myList = new List<string>();
    //copy the items from the array to the list
    myList.AddRange(array);
    //create the csv file if it does not exist
    if (!File.Exists("items.csv"))
    {
        File.Create("items.csv");
    }
    //open the file with a stream writer for editing
    using (var streamWriter = new StreamWriter("items.csv"))
    {
        foreach (var item in myList)
        {
            if (Int32.TryParse(item, out var res))
            {
                //append the item to the file and a line break
                streamWriter.Write(item+"\n");
            }
            else
            {
                //replace the comma in the current string with space
                var str = item.Replace(",", " ");
                //append the item and a comma
                streamWriter.Write(str+",");
            }
        }
    }
    

    Check the excel output of the file item.csv below. enter image description here