投げ銭

★当サイトへの投げ銭(PayPal)★

LINK


(無償、寄付歓迎) logo
世界中で使われるISO標準オフィスソフト(MSオフィス互換)

★LibreOfficeの導入事例★
詳細について

人気の投稿(1ヶ月間)

Ad

Ad

投げ銭

★当サイトへの投げ銭(PayPal)★

2017年9月3日日曜日

【.NET Core 2.0】CSVファイル(SHIFT-JIS)をCSVHelperで扱ってデータを汎用の型に格納するメソッドを作成する

<目次>
・既存のプロジェクトに CsvHelper を導入
・SHIFT-JISを利用できるように設定
・CSVファイルを読み込んで汎用の型にデータを格納するメソッドの作成


■準備

<CsvHelperの導入>

1、Visual Studio 2017 Communityで、既存のプロジェクトを開いた。
2、ツール → Nugetパッケージマネージャー → パッケージマネージャーコンソール を開いた。
3、下記のように、PM> プロンプトにコマンドを入力した。
各パッケージのライセンスは、パッケージの所有者からパッケージのユーザーに付与されます。NuGet は、サードパーティのパッケージに対して一切責任を負わず、いかなるライセンスも付与しません。パッケージに含まれている依存関係に対して追加のライセンスが適用されることがあります。依存関係を確認するには、パッケージ ソース (フィード) URL にアクセスしてください。
パッケージ マネージャー コンソール ホストのバージョン 4.4.0.4431
利用可能なすべての NuGet コマンドを参照するには、'get-help NuGet' を入力します。
PM> Install-Package CsvHelper
  GET https://api.nuget.org/v3/registration3-gz-semver2/csvhelper/index.json
  OK https://api.nuget.org/v3/registration3-gz-semver2/csvhelper/index.json 226 ミリ秒
C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\testWebApplication1.csproj のパッケージを復元しています...
  GET https://api.nuget.org/v3-flatcontainer/csvhelper/index.json
  OK https://api.nuget.org/v3-flatcontainer/csvhelper/index.json 2189 ミリ秒
  GET https://api.nuget.org/v3-flatcontainer/csvhelper/2.16.3/csvhelper.2.16.3.nupkg
  OK https://api.nuget.org/v3-flatcontainer/csvhelper/2.16.3/csvhelper.2.16.3.nupkg 708 ミリ秒
CsvHelper 2.16.3.0 をインストールしています。
NuGet パッケージ CsvHelper 2.16.3 をインストールしています。
復元をコミットしています...
ロック ファイルをディスクに書き込んでいます。パス: C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\obj\project.assets.json
C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\testWebApplication1.csproj の復元が 9.62 sec で完了しました。
'CsvHelper 2.16.3' が testWebApplication1 に正常にインストールされました
NuGet の操作の実行に 7.7 sec かかりました
経過した時間: 00:00:19.9191645
PM>

4、下記のように、利用する .cs コードファイルに、ネームスペースを追加した。
using CsvHelper;

<SHIFT-JIS を利用できるようにした>

○必要なパッケージと設定を行わなければ、次のように、System.Text.Encoding.GetEncoding("shift_jis") で例外が発生した。
An unhandled exception occurred while processing the request.
ArgumentException: 'shift_jis' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
System.Globalization.EncodingTable.internalGetCodePageFromName(string name)
System.Globalization.EncodingTable.internalGetCodePageFromName(string name)
System.Globalization.EncodingTable.GetCodePageFromName(string name)
System.Text.Encoding.GetEncoding(string name)

○そこで、次のように、パッケージの導入と設定を行った。

まず、パッケージの導入を行った。冒頭のCSVHelperの導入と同様である。
PM> Install-Package System.Text.Encoding.CodePages
  GET https://api.nuget.org/v3/registration3-gz-semver2/system.text.encoding.codepages/index.json
  OK https://api.nuget.org/v3/registration3-gz-semver2/system.text.encoding.codepages/index.json 186 ミリ秒
C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\testWebApplication1.csproj のパッケージを復元しています...
NuGet パッケージ System.Text.Encoding.CodePages 4.4.0 をインストールしています。
復元をコミットしています...
ロック ファイルをディスクに書き込んでいます。パス: C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\obj\project.assets.json
C:\Users\myname\source\repos\testWebApplication1\testWebApplication1\testWebApplication1.csproj の復元が 7.74 sec で完了しました。
NuGet の操作の実行に 7.7 sec かかりました
経過した時間: 00:00:17.7995284
PM>
そして、次のコードを、追加した。
位置は、System.Text.Encoding.GetEncoding("shift_jis") が実行される手前にした。
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
以下に、使用例としてメソッドを作成した。


■ CSVHelperの動作確認用メソッドの作成

CSVHelperはモデルマッピングなどの機能を有するが、
ここでは単純に、CSVファイルから、List<String[]> の形にデータを吸い出すようにした。

次のように、CSVファイルのパスを引数に与え、List<String[]> を返すメソッドを定義した。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Text;
using CsvHelper; 
private List<String[]> ConvCSVToArrayOfString(string filePath)
        {
            List<String[]> rows = new List<String[]>();
            List<string> fields = new List<string>();
            string value;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (TextReader fileReader = new StreamReader(filePath, System.Text.Encoding.GetEncoding("shift_jis")))
            {
                var csv = new CsvReader(fileReader);
                csv.Configuration.HasHeaderRecord = false;
                while (csv.Read())
                {
                    for (int i = 0; csv.TryGetField<string>(i, out value); i++)
                    {
                        //Adding a field to a collection
                        fields.Add(value);
                    }
                    //Adding this collection as String[] to a collection
                    rows.Add(fields.ToArray());
                    //Clear a list of fields
                    fields.Clear();
                } //Looping for a next row of CSV
            }
            return rows;
        }


新品価格
¥3,456から
(2018/5/21 15:43時点)

<参考>
(CSVHelperの導入と利用方法)
・CsvHelper
< http://joshclose.github.io/CsvHelper/ > 2017年9月1日

・C# で CSV を扱うのに CsvHelper を使う
< http://dany1468.hatenablog.com/entry/2013/07/15/175319 > 2017年9月1日


(CSVHelperの使用例)
・Read all values from CSV into a List using CsvHelper
< https://stackoverflow.com/questions/33294738/read-all-values-from-csv-into-a-list-using-csvhelper > 2017年9月1日

・Csvhelper - read / get a single column of all rows?
< https://stackoverflow.com/questions/18775745/csvhelper-read-get-a-single-column-of-all-rows > 2017年9月1日

・【C#】【CsvHelper】CsvHelperを利用したCsvファイルの生成
< http://kageura.hatenadiary.jp/entry/2015/05/18/200000 > 2017年9月1日

・CsvHelperとは
< http://notshown.hatenablog.jp/entry/2016/05/30/113815 > 2017年9月1日


(SHIFT-JISの導入について)
・Shift-JIS encoding for a netstandard library
< https://stackoverflow.com/questions/40331957/shift-jis-encoding-for-a-netstandard-library > 2017年9月1日

・System.Text.Encoding.CodePages 4.4.0
< https://www.nuget.org/packages/System.Text.Encoding.CodePages/ > 2017年9月1日

・EncodingProvider Class
< https://msdn.microsoft.com/en-us/library/system.text.encodingprovider(v=vs.110).aspx#Remarks > 2017年9月1日

・dotnet coreで対応しているテキストエンコーディング
< https://opcdiary.net/?p=31103 > 2017年9月1日

・.NET Core コンソールアプリで日本語出力する方法
< http://naughtldy.hatenablog.jp/entry/2017/05/01/080000 > 2017年9月1日

・.NET Core での コンソールアプリの文字化けを直す
< http://aquasoftware.net/blog/?p=895 > 2017年9月1日

・UWPでSJISを読みたい
< https://teratail.com/questions/56060 > 2017年9月1日


(StringReader)
・StreamReader vs TextReader
< https://forums.asp.net/t/1195587.aspx?StreamReader+vs+TextReader > 2017年9月1日

・文字コードを指定してテキストファイルを読み込む
< http://dobon.net/vb/dotnet/file/readfile.html > 2017年9月1日

・What is default encoding in .Net? #260
< https://github.com/dotnet/standard/issues/260 > 2017年9月1日


(CSVファイルをライブラリなしで扱う)
・Reading and Writing CSV Files in C#
< http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c > 2017年9月1日


(パッケージマネージャー)
・Package Manager Console
< https://docs.microsoft.com/ja-jp/nuget/tools/package-manager-console > 2017年9月1日

投げ銭

★当サイトへの投げ銭(PayPal)★

Ad

Ad