WPFでCSVファイルを出力

今回はWPFでCSVファイルを出力するプログラム制作にポンコツ2人組が挑戦してみました。 開発環境はVisualStudio2019を使用しました。

※この記事は2024/01/13時点の情報です。

MainWindow.xaml
ボタンを1つだけ配置しています。クリックするとCSVファイルを出力します。

<Window x:Class="WpfCsvExportSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CSV Export Sample" Height="350" Width="525">
    <Grid>
        <Button Content="CSVを出力するよ♪" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="50" Margin="10" Click="ExportToCsvButton_Click"/>
    </Grid>
</Window>

Person.cs
CSVファイルに出力するデータを格納するためのクラスです。 FirstName・LastName・Skillのプロパティを持っています。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfCsvExportSample
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Skill { get; set; }
    }
}

MainWindow.xaml.cs
初期処理でCSVファイルに出力するサンプルデータを作成します。 画面でボタンを押すと指定したファイルパスにCSVファイルが出力されます。 Encoding.GetEncodingで文字コード"shift_jis"と"UTF-8"のそれぞれでCSVファイルを出力します。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;

namespace WpfCsvExportSample
{
    public partial class MainWindow : Window
    {
        private List<Person> personList;

        public MainWindow()
        {
            InitializeComponent();
            // データを作成
            personList = new List<Person>
            {
                new Person { FirstName = "ポンコツ", LastName = "男子", Skill = "浅く広く" },
                new Person { FirstName = "ポンコツ", LastName = "女子", Skill = "記憶喪失" },
                new Person { FirstName = "黒猫", LastName = "アリス", Skill = "ひっかき" }
            };
        }

        private void ExportToCsvButton_Click(object sender, RoutedEventArgs e)
        {
            // データをShift_JISでCSVファイルに出力
            ExportToCsv("E:\\VisualStudioProject\\csv\\sample1.csv", personList, Encoding.GetEncoding("shift_jis"));
            // データをUTF-8でCSVファイルに出力
            ExportToCsv("E:\\VisualStudioProject\\csv\\sample2.csv", personList, Encoding.GetEncoding("UTF-8"));
        }

        private void ExportToCsv(string filePath, List<Person> data, Encoding encoding)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath, false, encoding))
                {
                    // ヘッダーを書き込む
                    sw.WriteLine("FirstName,LastName,Skill");

                    // データを書き込む
                    foreach (var person in data)
                    {
                        sw.WriteLine($"{person.FirstName},{person.LastName},{person.Skill}");
                    }

                    MessageBox.Show("CSVファイルが正常に出力されました。", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"エラーが発生しました: {ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}

以下がアプリケーションを実行した画面です。ボタンを押すと2つのCSVファイルが出力されました!

C#のWPFでCSV出力

以下は1つ目のCSVの内容です。ちゃんとデータが出力されていますね!

CSVの内容

管理人情報