Search code examples
c#csvcsvhelper

Write to CSV file using CsvHelper in C#


I tried to write to CSV file using CsvHelper in C#. This is the link to the library http://joshclose.github.io/CsvHelper/ Nothing is sent to the csv file. I tried doing "exportCsv.WriteField("Hello");" but still nothing happened.

List<string> ColumnOne = new List<string>();
List<string> ColumnTwo = new List<string>();
var csvTextWriter = new 
    StreamWriter(@"C:\Users\Public\Documents\ExportTest.csv");
var exportCsv = new CsvWriter(csvTextWriter);
    //creating a list to store workflows then adding name and description to the myWorkflowsList list
   if (myWorkflows.WorkFlowCollection.Any())
   {
        foreach (var Workflow in myWorkflows.WorkFlowCollection)
        {
                    ColumnOne.Add(Workflow.WorkflowName);
                    ColumnTwo.Add(Workflow.WorkflowDescription);
        }
        exportCsv.WriteField(ColumnOne);
        //exportCsv.WriteField(ColumnTwo);
        exportCsv.NextRecord();
        exportCsv.Flush();
        Console.WriteLine("File is saved: 
                C:\\Users\\Public\\Documents\\ExportTest.csv");
        Console.ReadLine();
    }

Solution

  • Your code doesn't add any records. It doesn't have any calls to WriteRecords or WriteRecord. It looks like it's trying to write an entire list of strings into a single field instead.

    To write two columns out to a file you can use `WriteRecords, eg :

    var data = from flow in myWorkflows.WorkFlowCollection
               select new { flow.WorkflowName,flow.WorkflowDescription};
    using (var writer = new StreamWriter("test.csv"))
    using (var csv = new CsvWriter(writer))
    {
        csv.WriteRecords(data);
    }
    

    This will write a file with field names WorkflowName and WorkflowDescription

    You can change how the fields are written by creating a small class that accepts only the fields you want and sets names etc through attributes :

    class Flow
    {
    
        [NameAttribute("Workflow Name")]
        public string WorkflowName { get; set; }
        [NameAttribute("Workflow Description")]
        public string WorkflowDescription { get; set; }
    
        public Flow(string workflowName, string workflowDescription)
        {
            WorkflowName = workflowName;
            WorkflowDescription = workflowDescription;
        }
    }
    
    
    //...
    var data = from flow in myWorkflows.WorkFlowCollection
               select new Flow(flow.WorkflowName,flow.WorkflowDescription);
    using (var writer = new StreamWriter("test.csv"))
    using (var csv = new CsvWriter(writer))
    {
        csv.WriteRecords(data);
    }