码迷,mamicode.com
首页 > 数据库 > 详细

直接把数据库中的数据保存在CSV文件中

时间:2016-03-23 16:50:09      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

                 今天突然去聊就来写一个小小的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();
        }
    }

直接把数据库中的数据保存在CSV文件中

标签:

原文地址:http://www.cnblogs.com/dyxd/p/5311666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!