データを定義する名前と場所だけのUserクラスを作成。
User.cs
namespace WpfApplication2
{
class User
{
public string Name { get; set; }
public string Place { get; set; }
public User(string name, string place)
{
this.Name = name;
this.Place = place;
}
}
}
WPFはCSV出力ボタンとDataGridの内容を表示するだけのシンプルなもの。
MainWindow.xaml
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<DataGrid Name="dataGrid" />
</StackPanel>
<StackPanel>
<Button Name="CSV" Content="CSV出力" Click="ExportCSV"/>
</StackPanel>
</Grid>
</Window>
MainWindows.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//サンプルデータ
data.Add(new User("太郎", "北海道"));
data.Add(new User("次\"郎", "岩手"));
data.Add(new User("三郎", "宮城"));
dataGrid.ItemsSource = data;
}
ObservableCollection<User> data = new ObservableCollection<User>();
//CSV出力ボタン押下時のイベント
private void ExportCSV(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
//保存先の初期値(マイドキュメント)
dlg.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
dlg.Title = "保存先のファイルを選択してください";
dlg.Filter = "CSVファイル(*.csv)|*.csv";
if(dlg.ShowDialog() == true){
try
{
using (var sw = new System.IO.StreamWriter(dlg.FileName, false, System.Text.Encoding.GetEncoding("Shift_JIS")))
{
//ダブルクォーテーションで囲む
Func<string, string> dqot = (str) => { return "\"" + str.Replace("\"", "\"\"") + "\""; };
foreach (User d in data)
sw.WriteLine(dqot(d.Name) + "," + dqot(d.Place));
}
MessageBox.Show("保存しました");
}
catch (SystemException ex)
{
System.Console.WriteLine(ex.Message);
}
}
}
}