private DataSet xsldata(string filepath,string extension) { string strConn = ""; switch (extension) { case ".xls": strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; case ".xlsx": strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; default: strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; } System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strConn); string strCom = "SELECT * FROM [Sheet1$]"; Conn.Open(); System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn); DataSet ds = new DataSet(); myCommand.Fill(ds, "[Sheet1$]"); // dataGridView1.DataSource = ds.Tables[0]; Conn.Close(); return ds; } /// <summary> /// 导入Sql数据库 /// </summary> /// <param name="filepath"></param> private void daoRu(string filepath,string Extente) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; SqlConnection conn = new SqlConnection(connectionString);//链接数据库 conn.Open(); try { DataSet ds = new DataSet(); //取得数据集 //调用上面的函数 ds = xsldata(filepath, Extente); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string cardtypeid = ds.Tables[0].Rows[i][0].ToString(); string cardnum = ds.Tables[0].Rows[i][1].ToString(); string cardpwd = ds.Tables[0].Rows[i][2].ToString(); string officeid = ds.Tables[0].Rows[i][3].ToString(); if (cardtypeid != "" && cardnum != "" && cardpwd != "" && officeid != "") { SqlCommand insertcmd = new SqlCommand("insert into StaffersTemp(EmpID,Depart,ChineseName,Isleave) values('" + cardtypeid + "','" + cardnum + "','" + cardpwd + "','" + officeid + "')", conn); insertcmd.ExecuteNonQuery(); } else { } } } catch (Exception ex) { } finally { conn.Close(); } }