using System; using System.Data; using System.IO; using System.Text; using System.Windows.Forms; namespace Sample { public partial class Form1 : Form { private readonly String[] Headers = { "姓名", "座號", "國文成績" }; private readonly String[] Users = { "王小明", "陳大吉", "洪船長" }; private readonly int[] CH_Score = { 57, 80, 92 }; private readonly int MAX = 3; private DataTable table = new DataTable(); public Form1() { InitializeComponent(); table.Columns.Add("Header"); table.Columns.Add("User"); table.Columns.Add("Score"); } private void button1_Click(object sender, EventArgs e) { for (int index = 0; index < MAX; index++) { DataRow row = table.NewRow(); row["Header"] = Headers[index]; row["User"] = Users[index]; row["Score"] = CH_Score[index]; table.Rows.Add(row); } DataTableToCSV(table); } private void DataTableToCSV(DataTable table) { StringBuilder builder = new StringBuilder(); foreach (var row in table.AsEnumerable()) { int maxLength = row.ItemArray.Length; for (int index = 0; index < maxLength; index++) if (index == maxLength - 1) builder.Append(String.Format("{0}{1}",row.ItemArray[index],Environment.NewLine)); else builder.Append(String.Format("{0},", row.ItemArray[index])); } File.WriteAllText(String.Format("{0}\\{1}.csv", Directory.GetCurrentDirectory(), DateTime.Now.Ticks), builder.ToString(), Encoding.UTF8); } } }
執行結果:
參考資料:
http://en.wikipedia.org/wiki/Comma-separated_values