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

Excel和SQLserver数据互相存取

时间:2015-08-25 23:55:48      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

      #region filed
        DataSet dataSet;
        #endregion

        #region Excel导出到DataBase
        /// <summary>
        ///从Excel中导入到到DataSet
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        public void ImportToDataBase(string filePath)
        {
            GetExcelData(filePath);
            WriteToDataSet();
        }
        /// <summary>
        ///从Excel中获取数据
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        void GetExcelData(string filePath)
        {
            string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                         "Data Source =" + filePath + ";" +
                         " Extended Properties='Excel 8.0;HDR = Yes;IMEX = 2'";
            string strSql = "select * from [Sheet1$]";
            OleDbConnection oleDbConnection = new OleDbConnection(strCon);
            OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(strSql, oleDbConnection);
            dataSet = new DataSet();
            oleDbConnection.Open();
            oleDbDataAdapter.Fill(dataSet);
            oleDbConnection.Close();
            dataSet=null;
            GC.Collect();
        }
        /// <summary>
        /// 将dataSet中的数据写入到DataBase
        /// </summary>
        void WriteToDataSet()
        {
            StringBuilder strbSql = new StringBuilder();
            string strCon = @"Data Source=PANLEE-PC\MSSQLSERVER_2;Initial Catalog=DBImage;Integrated Security=True";
            SqlConnection sqlConnection = new SqlConnection(strCon);
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = sqlConnection;
            sqlConnection.Open();

            try
            {
                string sqlCreate = @"Create Table Students(
                                   学号 varchar(50),
                                   姓名 varchar(50),
                                   专业班级 varchar(50),
                                   手机号码 varchar(50),
                                   )";
                sqlCommand.CommandText = sqlCreate;
                sqlCommand.ExecuteNonQuery();
            }
            catch { }

            for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
            {
                strbSql.Append("insert into Students(学号, 姓名, 专业班级, 手机号码) values('");
                for (int j = 0; j < 3; j++)
                {
                    strbSql.Append(dataSet.Tables[0].Rows[i].ItemArray[j].ToString() + "','");
                }
                strbSql.Append(dataSet.Tables[0].Rows[i].ItemArray[3].ToString() + "')");
                string strSql = strbSql.ToString();
                sqlCommand.CommandText = strSql;
                sqlCommand.ExecuteNonQuery();
                strbSql.Remove(0, strbSql.Length);
            }
            sqlConnection.Close();
        }
        #endregion

        #region DataBase导出到Excel

        public void ImportToExcel(string SaveFileName)
        {
            GetDataBaseData();
            CreateExcel(SaveFileName);
            WriteToExcel(SaveFileName);
        }

        /// <summary>
        ///从DataBase中获取数据到DataSet
        /// </summary>
        public void GetDataBaseData()
        {
            String strSql = "select * from Students";
            string strCon = @"Data Source=PANLEE-PC\MSSQLSERVER_2;Initial Catalog=DBImage;Integrated Security=True";
            SqlConnection sqlConnection = new SqlConnection(strCon);
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(strSql, strCon);
            dataSet = new DataSet(); 
            sqlConnection.Open();
            sqlDataAdapter.Fill(dataSet);
            sqlConnection.Close();
            dataSet = null;
            GC.Collect();
        }

        /// <summary>
        /// 创建Excel
        /// </summary>
        /// <param name="SaveFileName"></param>
        private void CreateExcel(string SaveFileName)
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wBook = excel.Application.Workbooks.Add(Missing.Value);
            excel.Visible = true;
            excel.DisplayAlerts = false;
            excel.AlertBeforeOverwriting = true;
            wBook.SaveAs(SaveFileName,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
            wBook = null;
            excel.Quit();
            excel = null;
        }

        /// <summary>
        /// 写入数据到Excel
        /// </summary>
        /// <param name="SaveFileName"></param>
        private void WriteToExcel(string SaveFileName)
        {

            string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                      "Data Source =" + SaveFileName + ";" +
                      " Extended Properties='Excel 8.0;HDR = Yes;IMEX = 2'";
            StringBuilder strbSql = new StringBuilder();
            OleDbConnection oleDbConnection = new OleDbConnection(strCon);
            OleDbCommand oleDbCom = new OleDbCommand();
            oleDbCom.Connection = oleDbConnection;
            oleDbConnection.Open();//学号, 姓名, 专业班级, 手机号码

            string strSql = "create table Sheet1 (学号 char(50),姓名 char(50), 专业班级 char(50),手机号码 char(50)) ";
            oleDbCom.CommandText = strSql;
            oleDbCom.ExecuteNonQuery();
            for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
            {
                strbSql.Append("insert into [Sheet1$] values('");
                for (int j = 0; j < 3; j++)
                {
                    strbSql.Append(dataSet.Tables[0].Rows[i].ItemArray[j].ToString() + "','");
                }
                strbSql.Append(dataSet.Tables[0].Rows[i].ItemArray[3].ToString() + "')");
                strSql = strbSql.ToString();
                oleDbCom.CommandText = strSql;
                oleDbCom.ExecuteNonQuery();
                strbSql.Remove(0, strbSql.Length);
            }
            oleDbConnection.Close();
        }
        #endregion

版权声明:本文为博主原创文章,未经博主允许不得转载。

Excel和SQLserver数据互相存取

标签:

原文地址:http://blog.csdn.net/ilipan/article/details/47984579

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