CsvHelperを使用して、CSVファイルを読み書きします。
CsvHelper のインストール
Visual Studio 2019のNuGet パッケージ マネージャーを使用してCsvHelper をインストールします。
Visual Studio の「ツール」 -> 「NuGet パッケージ マネージャー」 -> 「ソリューションの NuGet パッケージの管理」を選択します。
「参照」タブを選択して、検索欄に「CsvHelper」と入力して表示された「CsvHelper」を選択し、チェックボックスにチェックを入れて、「インストール」ボタンをクリックします。
CsvHelperのバージョン「27.2.1」 がインストールされました。
CSV読み書きソフトの作成
クラスマップを使ったCSV読み書きソフト「CsvHelperTest」を作成します。
- 16-33行目でCSVファイル「account.csv」を読み込み、コンソールにその内容を表示します。
- 37-54行目で、作成したデータをCSVファイル「sample.csv」に書き込みます。
CsvHelperTest
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
namespace CsvHelperTest
{
class Program
{
static void Main(string[] args)
{
using (var reader = new StreamReader("account.csv"))
{
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
//クラスマップを使って読み込み順序を指定します
csv.Context.RegisterClassMap<AccountMapper>();
// csv データが行毎に Foo クラスに格納され、IEnumerable<Foo> として
// records に割り当てられます。
var records = csv.GetRecords<Account>();
// records は IEnumerable なので、こんな使い方ができます。
foreach (var data in records)
{
Console.WriteLine("{0} : {1} : {2} : {3}", data.Name, data.Telephone1, data.Address1_city, data.Primarycontactid);
}
}
}
Console.ReadKey();
List<Hoge> list = new List<Hoge>();
list.Add(new Hoge { Id = 1, Name = "John" });
list.Add(new Hoge { Id = 2, Name = "Paul" });
list.Add(new Hoge { Id = 3, Name = "George" });
list.Add(new Hoge { Id = 4, Name = "Ringo" });
var config = new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture);
config.HasHeaderRecord = true;
config.ShouldQuote = (context) => true;
using (StreamWriter sw = new StreamWriter(@"sample.csv", false, Encoding.GetEncoding("Shift_JIS")))
{
using (var writer = new CsvWriter(sw, config))
{
writer.Context.RegisterClassMap<HogeMapper>();
writer.WriteRecords(list);
}
}
}
}
class Hoge
{
[Name("ユーザーID")]
public int Id { get; set; }
[Name("名前")]
public string Name { get; set; }
[Name("バージョン表記")]
[Constant("foo")]
public string Version { get; set; }
[Ignore]
public string Ignored { get; set; }
}
class HogeMapper : CsvHelper.Configuration.ClassMap<Hoge>
{
public HogeMapper()
{
AutoMap(CultureInfo.InvariantCulture);
}
}
/// <summary>
/// 格納用クラス
/// </summary>
public class Account
{
[Index(0)]
public string Name { get; set; }
[Index(1)]
public string Telephone1 { get; set; }
[Index(2)]
public string Address1_city { get; set; }
[Index(3)]
public string Primarycontactid { get; set; }
[Index(4)]
public string Numberofemloyees { get; set; }
}
/// <summary>
/// マッピング用クラス
/// </summary>
class AccountMapper : CsvHelper.Configuration.ClassMap<Account>
{
public AccountMapper()
{
Map(x => x.Name).Index(0);
Map(x => x.Telephone1).Index(1);
Map(x => x.Address1_city).Index(2);
Map(x => x.Primarycontactid).Index(3);
Map(x => x.Numberofemloyees).Index(4);
}
}
}
CSV読み書きソフトの実行
次の「account.csv」ファイルを実行ディレクトリに置き、CSV読み書きソフト「CsvHelperTest」を実行します。
account.csv
name,telephone1,address1_city,primarycontactid,numberofemployees Account1,80323287,Tokyo,test contact,10 Account2,3487984728,Osaka,test contact,12 Account3,34923487,Nagoya,test contact,332 ,,,,21
次の画面がコンソールに表示されます。
任意のキーを押すと、次の「sample.csv」ファイルが実行ディレクトリに作成されます。
sample.csv
"ユーザーID","名前","バージョン表記" "1","John","foo" "2","Paul","foo" "3","George","foo" "4","Ringo","foo"

