LoginSignup
1

More than 3 years have passed since last update.

CsvHelperの簡単な日付変換

Posted at

CsvHelperの簡単な日付変換で読み込む

CsvHelper 12.2.1

読み込むCSVの日付列が"20190101"のような形式だった時、属性で変換を指定して読み込む方法。
書き込みもたぶん同じ。試してない。

最初はClassMapを書いて読み込みをしていたが、日付を形式変換するためにClassMapを書くのは面倒だなと思って調べてたら、AttributesにFormatがあるなと気づいた話。

CsvHelper.Configuration.Attributes Namespace

100列とかあったとき、数列のためにClassMapを書くのはつかれるのでちょっとは楽になった。
ただ、何かに影響するかは知らない。

最初に書いていたソース

//File,Encoding,HasHeaderRecordはどっかで設定
public IEnumerable<CSV_Format> GetRecords()
{
    try
    {
        using (var reader = new StreamReader(File, Encoding.GetEncoding(EncodingName)))
        using (var csv = new CsvReader(reader))
        {
            csv.Configuration.HasHeaderRecord = HasHeaderRecord;
            csv.Configuration.RegisterClassMap<CSV_Format_Mapper>();
            return csv.GetRecords<CSV_Format>();
        }
    }
    catch (Exception ex)
    {
        //..例外処理..
    }
}
class CSV_Format_Mapper : ClassMap<CSV_Format>
    {
        public CSV_Format_Mapper()
        {
            Map(x => x.col1).Index(1);
            Map(x => x.col2).Index(2);
            Map(x => x.col4).Index(4).TypeConverterOption.Format("yyyyMMdd");
            Map(x => x.col6).Index(6);
        }
    }

    class CSV_Format
    {
        public string col1 { get; set; }
        public int col2 { get; set; }
        public DateTime col4 { get; set; }
        public decimal col6 { get; set; }
    }

Attributesを使ったソース

CSV_Format_Mapperを書かなくていい!

//File,Encoding,HasHeaderRecordはどっかで設定
public IEnumerable<T> GetRecords()
{
    try
    {
        using (var reader = new StreamReader(File, Encoding.GetEncoding(EncodingName)))
        using (var csv = new CsvReader(reader))
        {
            csv.Configuration.HasHeaderRecord = HasHeaderRecord;
            //csv.Configuration.RegisterClassMap<CSV_Format_Mapper>(); //いらなくなった
            return csv.GetRecords<T>();
        }
    }
    catch (Exception ex)
    {
        //..例外処理..
    }
}
class CSV_Format
{
    [Index(1)]
    public string col1 { get; set; }
    [Index(2)]
    public int col2 { get; set; }
    [Index(3), Format("yyyyMMdd")]
    public DateTime col4 { get; set; }
    [Index(4)]
    public decimal col6 { get; set; }
}

参考

Attributes
CsvHelper.Configuration.Attributes Namespace

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1