Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper parse csv and convert string to DateTime

Tags:

c#

csv

csvhelper

I am working with CsvHelper and being able to parse csv file. My question is how can I parse the Date into DateTime object

I want to convert it via CsvHelper while it is parsing the csv rather than iterating the collection

public static List<StockModel> SplitCsv(string csv)
{
    var textReader = new StringReader(csv);

    var csvr = new CsvReader(textReader);
    csvr.Configuration.RegisterClassMap<ModelMap>();

    var records = csvr.GetRecords<StockModel>().ToList();
    return records;
}

public class StockModel
{
    public string Date { get; set; } // I want this object to be DateTime
    public string Base { get; set; }
    public string Open { get; set; }
}

public sealed class ModelMap : CsvClassMap<StockModel>
{
    public ModelMap()
    {
        Map(m => m.Date);
        Map(m => m.Base);
        Map(m => m.Open);
    }
}

CSV example

Date,Base,Open
2016-02-29,1437.530029,1445.839966
2016-02-25,1431.439941,1431.439941
2016-02-24,1430.459961,1432.430054
like image 740
user829174 Avatar asked Mar 14 '16 14:03

user829174


1 Answers

From my understanding of CsvHelper, The default built in converters will handle most cases of type conversion where it should be able to convert the type of the properties of your class. No need to make them all strings. Just put them in the type you want. Once the property name matches the column name (if present) in the csv then it auto maps those fields to their matching property

public class StockModel
{
    //2016-02-29
    public DateTime Date { get; set; } // CsvHelper should be able to infer type
    //1437.530029
    public decimal Base { get; set; }
    //1445.839966
    public decimal Open { get; set; }
}


public static List<StockModel> SplitCsv(string csv)
{
    var textReader = new StringReader(csv);

    var csvr = new CsvReader(textReader);

    var records = csvr.GetRecords<StockModel>().ToList();

    return records;
}

From Wiki on github

Using CsvHelper is really easy. It's default settings are setup for the most common scenarios.

Here is a little setup data.

Actors.csv:

Id,FirstName,LastName  
1,Arnold,Schwarzenegger  
2,Matt,Damon  
3,Christian,Bale

Actor.cs (custom class object that represents an actor):

public class Actor
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Reading

Reading the CSV file using CsvReader:

var csv = new CsvReader( new StreamReader( "Actors.csv" ) );
var actorsList = csv.GetRecords<Actor>();
like image 88
Nkosi Avatar answered Nov 13 '22 11:11

Nkosi