【C#】CSVファイルを読み込む

PR

前提

1.読み込むcsvファイルは「楽天カードの利用明細」。フォーマットは以下。
 ┗1行目に項目名
 ┗2行目から利用店名や利用金額など
 ┗「”(ダブルコーテーション)」で括られている


2.0列目から数えて、「利用店名(1列目)」毎の「利用金額(4列目)」を集計する

PR

サンプルコード

(省略)

private void Button_Click(object sender, RoutedEventArgs e)
{
    //クレジットカード明細の抜粋を設定するDictionary
    Dictionary<string, double> crediCardStatement = new Dictionary<string, double>();

    //csvファイル名
    string csvFile = "C:\\Users\\user\\Desktop\\rakutenInput\\enavi201908(1286).csv";

    //csv読み込み
    using (var sr = new System.IO.StreamReader(@csvFile, System.Text.Encoding.GetEncoding("shift_jis")))
    {
        double userAmountTemp;
        //利用店名の列
        const int useStoreNamePos = 1;
        //利用金額の列
        const int userAmountPos = 4;

        //1行読み捨てる
        sr.ReadLine();

        while (!sr.EndOfStream)
        {
            //1行読み込む
            string line = sr.ReadLine();

            //カンマ毎に分けて配列に格納
            string[] values = line.Split(',');

            //利用店名と利用金額を取得 ※「"(ダブルコーテーション)」を削除
            string useStoreName = values[useStoreNamePos].Trim(new char[] { '"' });
            double userAmount = double.Parse(values[userAmountPos].Trim(new char[] { '"' }));

            //Dictionaryへ設定
            if (crediCardStatement.ContainsKey(useStoreName))
            {
                userAmountTemp = crediCardStatement[useStoreName];
                crediCardStatement[useStoreName] = userAmountTemp + userAmount;
            }
            else
            {
                crediCardStatement.Add(useStoreName, userAmount);
            }
        }
    }

    //Dictionaryの内容を出力画面に出力し確認
    foreach (string useStoreName in crediCardStatement.Keys)
    {
        System.Diagnostics.Trace.WriteLine(useStoreName + " : " + crediCardStatement[useStoreName]);
    }
}
PR

実行結果


PR

参考

VBAによりCSVファイルをExcelのシートへ読み込むこともできます。
詳細は以下の記事をご確認ください。




逆に、Excelのシートの内容をCSVファイルへ出力することもできます。
詳細は以下の記事をご確認ください。

タイトルとURLをコピーしました