はじめに
http://joshclose.github.io/CsvHelper/
「CsvHelper」をプロジェクトに追加することで
CSV の読み書きができるようになります
インストール
Visual Studio メニューの「ツール>NuGet パッケージ マネージャー>
ソリューションの NuGet パッケージの管理」を選択します
「参照」タブを選択して、検索欄に「CsvHelper」と入力して
表示された「CsvHelper」を選択します
インストールしたいプロジェクトをチェックして「インストール」ボタンを押します
CSV の読み込み
number,name,species,height,weight 1,フシギダネ,たねポケモン,0.7,6.9 2,フシギソウ,たねポケモン,1.0,13.0 3,フシギバナ,たねポケモン,2.0,100.0
このような CSV を読み込みたい場合、下記のようなコードを記述します
using CsvHelper; using CsvHelper.Configuration; using System; using System.IO; internal class Pokemon { public int number { get; set; } public string name { get; set; } public string species { get; set; } public float height { get; set; } public float weight { get; set; } } internal class PokemonTable : ClassMap<Pokemon> { private PokemonTable() { Map( c => c.number ).Index( 0 ); Map( c => c.name ).Index( 1 ); Map( c => c.species ).Index( 2 ); Map( c => c.height ).Index( 3 ); Map( c => c.weight ).Index( 4 ); } } public static class Program { private static void Main() { var path = @"【CSV ファイルのパス】"; using ( var csv = new CsvReader( new StreamReader( path ) ) ) { var config = csv.Configuration; config.HasHeaderRecord = true; // ヘッダーが存在する場合 true config.RegisterClassMap<PokemonTable>(); var list = csv.GetRecords<Pokemon>(); foreach ( var n in list ) { Console.WriteLine( $"{n.number}, {n.name}, {n.species}, {n.height}, {n.weight}" ); } } } }
CSV の書き込み
下記のようなコードで CSV ファイルの出力が可能です
using CsvHelper; using CsvHelper.Configuration; using System.IO; internal class Pokemon { public int number { get; set; } public string name { get; set; } public string species { get; set; } public float height { get; set; } public float weight { get; set; } public Pokemon ( int number , string name , string species , float height , float weight ) { this.number = number ; this.name = name ; this.species = species ; this.height = height ; this.weight = weight ; } } internal class PokemonTable : ClassMap<Pokemon> { private PokemonTable() { Map( c => c.number ).Index( 0 ); Map( c => c.name ).Index( 1 ); Map( c => c.species ).Index( 2 ); Map( c => c.height ).Index( 3 ); Map( c => c.weight ).Index( 4 ); } } public static class Program { private static void Main() { var list = new [] { new Pokemon( 1, "フシギダネ", "たねポケモン", 0.7f, 6.9f ), new Pokemon( 2, "フシギソウ", "たねポケモン", 1.0f, 13.0f ), new Pokemon( 3, "フシギバナ", "たねポケモン", 2.0f, 100.0f ), }; var path = "pokemon.csv"; using ( var csv = new CsvWriter( new StreamWriter( path ) ) ) { var config = csv.Configuration; config.HasHeaderRecord = true; // ヘッダーが存在する場合 true config.RegisterClassMap<PokemonTable>(); // 区切り文字をタブとかに変えることも可能 //config.Delimiter = "\t"; csv.WriteRecords( list ); } } }