14
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# > CSV取り込みを劇的に簡単にするCsvHelper

Last updated at Posted at 2019-04-16

CSV取り込みしたのち、クラスにマッピングしてくれるライブラリ「CsvHelper」
NugetからCsvHelperを取得後、以下のように使う

列名を指定する方法



using System;
using CsvHelper.Configuration.Attributes;
public class CsvEntity
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}


using CsvHelper;
public static List<CsvEntity> GoLoad(string csvFileFullPath)
{
    var result = new List<CsvEntity>();
    using (var reader = new StreamReader(csvFileFullPath)){
    using (var csv = new CsvReader(reader))
    {
        csv.Read();
        csv.ReadHeader();
        while (csv.Read())
		{
            var record = new CsvEntity
            {
                Field1 = csv.GetField("ColumnName1"),
                Field2 = csv.GetField("ColumnName2")
            };
            result.Add(record);
        }
    }
	return result;
}

Attributesを使用する方法

using System;
using CsvHelper.Configuration.Attributes;
public class CsvEntity
{
    [Name("ColumnName1")]
    public string Field1 { get; set; }

    [Name("ColumnName2")]
    public string Field2 { get; set; }
}


using CsvHelper;
public static List<CsvEntity> GoLoad(string csvFileFullPath)
{
    var result = new List<CsvEntity>();
    using (var reader = new StreamReader(csvFileFullPath))
    {
        using (var csv = new CsvReader(reader))
        {
            csv.Read();
            csv.ReadHeader();
            var records = csv.GetRecords<CsvEntity>();
            foreach (var record in records)
            {
                 result.Add(record);
            }
        }
    }
    return result;
}

Shift_JIS

Shift_JISでCSVを読み込む必要がある場合には、
System.Text.Encoding.CodePagesをNugetから取得したのち、

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (var reader = new StreamReader(csvFileFullPath, Encoding.GetEncoding("Shift_JIS")))

参考

CsvHelper

14
21
0

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
14
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?