日期:2014-05-17 浏览次数:20361 次
net Excel数据导入到数据库 .net Excel数据导入到数据库 一.数据库向导本来就可以这样导入,在Excel建的字段,必须在table表中也得有字段. 二.读取excel文件中的数据 先在类中定义一个方法名为ExecleDs的方法,用于将Excel表里的数据填充到DataSet中,代码如下: public DataSet ExecleDs(string filenameurl,string table) { string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" +filenameurl+ ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]",conn); DataSet ds = new DataSet(); odda.Fill(ds,table); return ds; } 当点击添加按钮时激发事件,代码如下 protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile == false) { Response.Write("<script>alert('请您选择Excel文件')</script> "); return;//当无文件时,返回 } string IsXls=System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower(); if (IsXls != ".xls") { Response.Write("<script>alert('只可以选择Excel文件')</script>"); return;//当选择的不是Excel文件时,返回 } string error = null; Access.Class1 ac = new Access.Class1(); SqlConnection cn = ac.myConnection(); cn.Open(); string strpath = FileUpload1.PostedFile.FileName.ToString(); //获取Execle文件路径 string filename = FileUpload1.FileName; //获取Execle文件名 DataSet ds = ac.ExecleDs(strpath,filename); DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组 int rowsnum = ds.Tables[0].Rows.Count; if (rowsnum == 0) { Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示 } else { for (int i = 0; i < dr.Length; i++) { string YHMC = dr[i]["YongHuMingCheng"].ToString(); string YHMM = dr[i]["YongHuMiMa"].ToString(); string DQRQ = dr[i]["DaoQiRiQi"].ToString(); string ZT = dr[i]["ZhuangTai"].ToString(); string TJSJ = dr[i]["TianJiaShiJian"].ToString(); string JXDM = dr[i]["JiaXiaoDaiMa"].ToString(); string sqlcheck = "select count(*) from DC_YongHuLieBiao where YongHuMingCheng='" + YHMC + "'And JiaXiaoDaiMa='" + JXDM + "'"; //检查用户是否存在 bool ch = ac.check(sqlcheck); if (ch == true) { string insertstr = "insert into DC_YongHuLieBiao(YongHuMingCheng,YongHuMiMa,DaoQiRiQi,ZhuangTai,TianJiaShiJian,JiaXiaoDaiMa) values('" + YHMC + "','" + YHMM + "','" + DQRQ + "','" + ZT + "','" + TJSJ + "','" + JXDM + "')"; SqlCommand cmd = new SqlCommand(insertstr,cn); try { cmd.ExecuteNonQuery(); } catch (MembershipCreateUserException ex) //捕捉异常 { Response.Write("<script>alert('创建用户:"+ex.Message+"')</script>"); } } else { error += "<em style='color:red;font-sixe:25px'>"+YHMC+"</em>用户