分享

SqlServ数据r导入到Excel完整源码

 悟静 2012-01-31

#region  SqlServer导入到Excel

        //新创建的Excel文件路径
        public string strSaveFileName;
        //存放SqlServer内容
        public DataSet dsSqlServer;

        /// <summary>
        /// 选择Excel的保存路径
        /// </summary>
        /// <returns>已经选择好文件路径则返回true, 否则false</returns>
        public bool ChoicePath()
        {
            //保存对话框
            SaveFileDialog savePath = new SaveFileDialog();
            if (savePath.ShowDialog() == DialogResult.OK)
            {
                strSaveFileName = savePath.FileName;
                //判断文件是否已存在
                if (IsExist(strSaveFileName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 判断文件是否已存在,存在则询问是否覆盖
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns>“不存在”或“存在并允许覆盖”返回true, 存在但不覆盖返回false</returns>
        public bool IsExist(string fileName)
        {
            //判断文件是否已存在  
            if (System.IO.File.Exists(fileName + ".xls"))  
           {   //提示是否覆盖  
               if (MessageBox.Show("该文件已经存在,是否覆盖?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)  
               {
                   return false; 
               }  
               else 
               {   //删除已有文件   
                   System.IO.File.Delete(fileName + ".xls");
                   return true;
               }  
           }
           return true;
        }

        /// <summary>
        /// 获取SqlServer内容,存放到dsSqlServer里面
        /// </summary>
        public void GetDs()
        {
            //要执行的sql语句
            String strSql = "select * from CutClassTable";
            //SqlServer连接语句,该实例数据库为“MyDataBase”
            string strCon = @"Data Source=Localhost;Initial Catalog=MyDataBase;Integrated Security=True";
            //创建连接
            SqlConnection sqlCon = new SqlConnection(strCon);
            //.......
            SqlDataAdapter sqlDa = new SqlDataAdapter(strSql, strCon);
            dsSqlServer = new DataSet();
            sqlCon.Open();
            sqlDa.Fill(dsSqlServer, "Info");
            sqlCon.Close();
        }

        /// <summary>
        /// 创建Excel文件,在我的其它文章里,有讲这方面内容,不清楚的可翻看前面章节
        /// </summary>
        private void CreateExcel()
        {
            try
            {
                //创建Excel对象
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                //创建新的Excel工作簿
                Microsoft.Office.Interop.Excel.Workbook wBook = excel.Application.Workbooks.Add(Missing.Value);
                //使Excel不可视         
                excel.Visible = false;

                //设置禁止弹出保存和覆盖的询问提示框
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = true;

                //保存
                wBook.SaveAs(@strSaveFileName,
                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
                excel.Quit();  
                excel = null;

            }
            catch (Exception err)
            {
                //错误提示
                MessageBox.Show("Excel操作出错!错误原因:" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
               
            }
        }

        /// <summary>
        /// 把数据导入Excel
        /// </summary>
        private void InsertToExcel()
        {
            //下面是Excel数据库访问操作:
            //连接字符串
            string strCon = @"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = '" + strSaveFileName + "';Extended Properties='Excel 8.0;HDR=NO'";
            //要执行的sql语句,采用stringbuilder类
            StringBuilder strbSql = new StringBuilder();
            //创建OleDb连接对象.
            OleDbConnection oleDbCon = new OleDbConnection(strCon);
            //创建执行对象
            OleDbCommand oleDbCom = new OleDbCommand();
            //赋予连接对象
            oleDbCom.Connection = oleDbCon;
            //打开连接
            oleDbCon.Open();
            //下面是数据插入到Excel
            try
            {
                //创建一张新的工作表,表名为MySheet。你或许疑惑为什么不在原有的工作区Sheet1里导入,在后面我会讲到!
                string strSql = "create table MySheet (学号 char(20), 姓名 char(20), 旷课次数 int, 原因 char(255)) ";
                //赋予sql语句
                oleDbCom.CommandText = strSql;
                //执行sql语句,创建一个新表
                oleDbCom.ExecuteNonQuery();
                //循环插入数据
                for (int i = 0; i < dsSqlServer.Tables[0].Rows.Count; i++)
                {
                    //要注意 参数要用 ' '括起来的。例如: 'value'
                    strbSql.Append("insert into [MySheet$] values('");
                    for (int j = 0; j < 3; j++)
                    {
                        strbSql.Append(dsSqlServer.Tables[0].Rows[i].ItemArray[j].ToString() + "','");
                    }
                    strbSql.Append(dsSqlServer.Tables[0].Rows[i].ItemArray[3].ToString() + "')");
                    //stringbuilder转为string类型,因为sql语句不能直接执行stringbuilder类
                    strSql = strbSql.ToString();
                    oleDbCom.CommandText = strSql;
                    oleDbCom.ExecuteNonQuery();
                    //清除strbSql过往信息
                    strbSql.Remove(0, strbSql.Length);
                }
                //插入成功提示
                MessageBox.Show("导入Excel成功!请查看!:", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                //失败提示
                MessageBox.Show("导入Excel过程中发生错误!/n错误提示:" + ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                oleDbCon.Close();
            }
           
        }

        /// <summary>
        /// 导入数据到Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntToExcel_Click(object sender, EventArgs e)
        {
            //判断是否选择好路径
            if (ChoicePath())
            {
                //创建一个Excel文件
                CreateExcel();
                //获取SqlServer表内容,存放到dsSqlServer里面
                GetDs();
                //导入数据到Excel
                InsertToExcel();
            }
        }

        #endregion

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多