概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
DataTableを、CSV出力せよ。
写真
サンプルコード
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
class form1: Form {
ComboBox comboBox1;
DataTable dt;
DataGridView gd0;
form1() {
Text = "csv out";
ClientSize = new Size(400, 300);
comboBox1 = new ComboBox();
comboBox1.Location = new Point(120, 10);
comboBox1.Size = new Size(100, 25);
comboBox1.Items.Add("");
comboBox1.Items.Add("赤");
comboBox1.Items.Add("黄");
comboBox1.Items.Add("紫");
comboBox1.Items.Add("橙");
comboBox1.Items.Add("緑");
comboBox1.SelectedIndex = 0;
comboBox1.SelectedValueChanged += comboBox1_SelectedIndexChanged;
dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Iro", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "赤", "りんご");
dt.Rows.Add(2, "黄", "バナナ");
dt.Rows.Add(3, "黄", "レモン");
dt.Rows.Add(4, "赤", "トマト");
dt.Rows.Add(5, "紫", "ぶどう");
dt.Rows.Add(6, "橙", "みかん");
dt.Rows.Add(7, "橙", "柿");
dt.Rows.Add(8, "緑", "めろん");
gd0 = new DataGridView();
gd0.Location = new Point(20, 40);
gd0.Size = new Size(350, 250);
gd0.DataSource = dt;
Button btn1 = new Button();
btn1.Location = new Point(250, 10);
btn1.Text = "csv出力";
btn1.Click += btn1_Click;
Controls.AddRange(new Control[] {
comboBox1,
btn1,
gd0
});
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
string str = "Iro = '" + comboBox1.SelectedItem.ToString() + "'";
DataTable _newFilteredDataTable = dt.Select(str).CopyToDataTable();
gd0.DataSource = _newFilteredDataTable;
}
void btn1_Click(object sender, System.EventArgs e) {
Encoding enc = Encoding.GetEncoding("Shift_JIS");
using (StreamWriter sr = new StreamWriter("dt8.csv", true, enc))
{
foreach (DataRow row in dt.Rows)
{
sr.WriteLine(string.Join(",", row.ItemArray));
}
}
}
[STAThread]
public static void Main() {
Application.Run(new form1());
}
}
実行結果
>type dt8.csv
1,赤,りんご
2,黄,バナナ
3,黄,レモン
4,赤,トマト
5,紫,ぶどう
6,橙,みかん
7,橙,柿
8,緑,めろん
以上。