18
23

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を使って読み込んでみた。

このような形のcsvファイルを読み込んで、表示とListにする処理。

リュウ,1964-07-21,Male
ケン,1965-02-14,Male
ガイル,1960-12-23,Male
春麗,1968-03-01,Female
サガット,1955-07-02,Male
ダルシム,1952-11-22,Male
ザンギエフ,1956-06-01,Male
豪鬼,,Male

まず、カラムの定義。

public enum Gender{Male,Female,Unknown}
public class Columns
{
	public string Name{ get; set;}
	public Nullable<DateTime> Date{ get; set;}
	public Gender gender{ get; set;}
}

このcsvは名前と日付と性別なので、以下のクラスを定義する。

次にマッピング

public sealed class AccountMap : CsvHelper.Configuration.CsvClassMap<Columns>
{
	public AccountMap()
	{
		Map (x => x.Name).Index (0);
		Map (x => x.Date).Index (1);
		Map (x => x.gender).Index (2);
	}
}

これで、csvをインデックスごとに分割できる

実際の処理はこんな感じ

using (var csv = new CsvHelper.CsvReader(new StreamReader (filename)))
{
	csv.Configuration.HasHeaderRecord = false; // Headerはなし
	csv.Configuration.RegisterClassMap<AccountMap> ();
	var records = csv.GetRecords<Columns> ();
	foreach (var item in records)
	{
		Console.WriteLine ("{0},{1},{2}",item.Name,item.Date,item.gender);
	}
}

これで、行ごとの要素を出力できる。

Listに持たせる場合はこんな感じ

using (var parse = new CsvHelper.CsvParser (new StreamReader (filename))) 
{
	parse.Configuration.HasHeaderRecord = false;
	parse.Configuration.RegisterClassMap<AccountMap> ();
	var reader = new CsvHelper.CsvReader (parse);
	List<Columns> data = reader.GetRecords<Columns>().ToList ();
}

これでdataはリストが生成されているはず

18
23
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
18
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?