将Excel(.xlsx)中的数据导入到数据库中

        string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES;IMEX=1';Data Source=shengshi.xlsx";//文件放到哪里,调试时可以看出。

        private bool InsertCity()
        {
            try
            {
                OleDbDataAdapter dr = new OleDbDataAdapter("select * from [InfoCity$]", connStr);
                DataSet dt = new DataSet();
                dr.Fill(dt);
                dr.Dispose();

                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    string testSql = string.Format("insert into city(provinceId,cityId,cityName) values('{0}','{1}','{2}')", dt.Tables[0].Rows[i]["provinceId"].ToString(), dt.Tables[0].Rows[i]["cityId"].ToString(), dt.Tables[0].Rows[i]["cityName"].ToString());
                   ServiceManager.UserBuyCarService.InsertCity(testSql);
                }
            }
            catch (Exception ex)
            {
                throw new QiPeiException(ex.Message);
            }
            return false;
        }

 

posted @ 2015-04-14 16:19  aspnet_如月  阅读(585)  评论(0编辑  收藏  举报