Search code examples
c#model-view-controllerdictionarycsvhelper

CSVHelper C# Load from My object


Hi I am trying to use CSVHelper to simply export to CSV a list of objects. (http://joshclose.github.io/CsvHelper)

So I have this:

List<Employee> employeeList = GetAllEmployees();

I created this map:

public sealed class EmployeeExport: CsvClassMap<Employee>
{
    public EmployeeExport()
    {
        Map(m => m.Id);
        Map(m => m.Date).TypeConverterOption("dd/MM/yyyy");
        Map(m => m.Account.AccountName);
        Map(m => m.LabourChargeType.LabourChargeTypeName);
    }
}

How can I load the ExployeeExport class with my employeeList and simply export to CSV according to my Map class?

Also how can I convert my Employee.Minutes to "hh:mm" and creating a new column inexistent called "Duration"

Thanks


Solution

  • I think the mapping is for reading CSV. you will need to include "using System.IO"

    EDIT:

            // Populate your employeeList
            TextWriter textWriter = new StreamWriter("foo.csv"); //foo.csv is the file you are saving to
            var csv = new CsvWriter(textWriter);
            foreach (var employee in employeeList)
            {
                csv.WriteField(employee.Id);
                csv.WriteField(employee.Date.ToShortDateString());
                csv.WriteField(employee.Account.AccountName);
                csv.WriteField(employee.LabourChargeType.LabourChargeTypeName);
                csv.NextRecord();
            }
            textWriter.Flush();
            textWriter.Close();
            textWriter = null;
    

    REFERENCE: http://csharp.net-informations.com/file/csharp-textwriter.htm