1
0

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 1 year has passed since last update.

[C#] DataTableのCSV出力の短縮

Last updated at Posted at 2024-02-26

C#のCSV出力が短縮できたのでメモ

今までは(https://dobon.net/vb/dotnet/file/writecsvfile.html)
に記載されている書き方で作成していた。

    //CSVファイルに書き込むときに使うEncoding
    System.Text.Encoding enc =System.Text.Encoding.GetEncoding("Shift_JIS");

    //書き込むファイルを開く
    System.IO.StreamWriter sr = new System.IO.StreamWriter(csvPath, false, enc);

    int colCount = dt.Columns.Count;
    int lastColIndex = colCount - 1;

    //レコードを書き込む
    foreach (DataRow row in dt.Rows)
    {
        for (int i = 0; i < colCount; i++)
        {
            //フィールドの取得
            string field = row[i].ToString();
            //"で囲む
            field = EncloseDoubleQuotesIfNeed(field);
            //フィールドを書き込む
            sr.Write(field);
            //カンマを書き込む
            if (lastColIndex > i)
            {
                sr.Write(',');
            }
        }
        //改行する
        sr.Write("\r\n");
    }

    //閉じる
    sr.Close();

以下のように短縮することができた


    //CSVファイルに書き込むときに使うEncoding
    Encoding enc = Encoding.GetEncoding("Shift_JIS");
    
    //書き込むファイルを開く
    using (StreamWriter sr = new StreamWriter(strOutputPath, true, enc))
    {
        //レコードを書き込む
        foreach (DataRow row in ds.dtOutput.Rows)
        {
            sr.WriteLine(string.Join(",", row.ItemArray));
        }
    }

・解説

//sr.Write → sr.WriteLineで、改行も含むように
sr.WriteLine(...
//1行単位のcsvを作成
string.Join(",", row.ItemArray)
1
0
3

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?