日期:2014-05-18  浏览次数:20798 次

把Excel中的数据导到数据库中怎么实现啊?解决方案也行。。。求解
把Excel中的数据导到数据库中怎么实现啊?解决方案也行。。。,有源码的例子最好

------解决方案--------------------
读取Excel数据到DataSet就行了。
------解决方案--------------------
C# code
/// <summary>
        /// 解析Excel,根据OleDbConnection直接连Excel
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static DataSet LoadDataFromExcel(string filePath, string name)
        {
            try
            {
                string strConn;
                //   strConn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filePath + ";Extended Properties=Excel 8.0";
                strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=No\"";
               OleDbConnection  OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                string sql = "SELECT * FROM [" + name + "$]";//可是更改Sheet名称,比如sheet2,等等  
                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, name);
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                MessageBox.Show("数据绑定Excel失败! 失败原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }
        }

------解决方案--------------------
C# code
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=U8单价维护.xlsx;Extended Properties='Excel 12.0;IMEX=1'";
                using (OleDbConnection conn = new OleDbConnection(excelConnectionString))
                {
                    OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [new$]", conn);
                    adapter.Fill(ds, "excel");
                }
                //Console.WriteLine("Excel数据:" + ds.Tables[1].Rows[0][0].ToString());