EXCEL导入数据库

 if (!(FileUpload1.HasFile))
            {
                Common.MessageBox.Show(this, "请选择文件!");
                return;
            }
            if (System.IO.Path.GetExtension(FileUpload1.FileName.ToString()) != ".xls")
            {
                Common.MessageBox.Show(this, "只能上传.xls的Excel文件!");
                return;
            }

             string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            string filesave = Server.MapPath("/upload/" + filename);
            FileUpload1.SaveAs(filesave);
            DataSet ds = LoadDataFromExcel(filesave);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("insert into xx());
                sb.Append("values(");
                sb.Append();
                Socut.Data.ExecuteNonQuery(sb.ToString());
            }

           // MessageBox.Show(this, "导入完成!");
public static DataSet LoadDataFromExcel(string filePath)
        {          
            try     
            {       
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();   
                String sql = "SELECT * FROM  [Sheet1$]";//可更改Sheet名称,比如sheet2,等等 
                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);  
                DataSet OleDsExcle = new DataSet();  
                OleDaExcel.Fill(OleDsExcle, "Sheet1");   
                OleConn.Close();        
                return OleDsExcle;           
            }          
            catch (Exception err) 
            {
                HttpContext.Current.Response.Write("数据绑定Excel失败!失败原因:" + err.Message);
                return null;      
            }    
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值