今天突然去聊就来写一个小小的demo喽,嘿嘿
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "CSV文件|*.CSV"; saveFileDialog1.InitialDirectory = "D:\\20160323"; if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) { return; } else { DataSet ds = GetTables(); string fileName1 = "Blogs"; string fileName2 = "AspNetUsers"; string fileName3 = "AspNetUserRoles"; SaveCSV(ds.Tables[0], fileName1); SaveCSV(ds.Tables[1], fileName2); SaveCSV(ds.Tables[2], fileName3); MessageBox.Show("CSV文件保存成功!"); } } public DataSet GetTables() { string sql = @"select * from Blogs; select * from AspNetUsers; select * from AspNetUserRoles "; SqlParameter[] parms = { }; return SqlHelper.ExecutedataAdapter(sql, parms, CommandType.Text); } /// <summary> /// 将DataTable中数据写入到CSV文件中 /// </summary> /// <param name="dt">提供保存数据的DataTable</param> /// <param name="fileName">CSV的文件路径</param> public void SaveCSV(DataTable dt, string fileName) { FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); string data = ""; //写出列名称 for (int i = 0; i < dt.Columns.Count; i++) { data += dt.Columns[i].ColumnName.ToString(); if (i < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); //写出各行数据 for (int i = 0; i < dt.Rows.Count; i++) { data = ""; for (int j = 0; j < dt.Columns.Count; j++) { data += dt.Rows[i][j].ToString(); if (j < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); } sw.Close(); fs.Close(); } }
时间: 2024-10-28 23:13:59