asp.net中导入Excel
DataTable table; try { this.Label1.Text = ""; if (this.FileUpload1.HasFile) { DataTable inputdt = new DataTable(); int len = this.FileUpload1.FileName.ToString().Trim().Length; path = Server.MapPath(".") + "/" + "o" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".xls"; this.FileUpload1.SaveAs(path); //上传文件 string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + path + "';Extended Properties=Excel 8.0"; OleDbConnection cnnxls = new OleDbConnection(mystring); OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls); DataSet myDs = new DataSet(); myDa.Fill(myDs); table = myDs.Tables[0]; SqlConnection mySqlConn = db.create(); mySqlConn.Open(); string strCmd = ""; int rows = myDs.Tables[0].Rows.Count; int cols = myDs.Tables[0].Columns.Count; for (int i = 0; i < rows; i++) { strCmd = "insert 单位招聘信息表 (招考单位编号,招考单位,职位编号,职位名称,录用名额,招考范围,专业,年龄,学历,其他,联系电话,是否加考专业科目,开考比例)values('"; for (int j = 0; j < cols; j++) { if (j == 0) { strCmd = strCmd + myDs.Tables[0].Rows[i].ItemArray[j].ToString(); } else { strCmd += "','" + myDs.Tables[0].Rows[i].ItemArray[j].ToString(); } } strCmd += "')"; SqlCommand mySqlCmd = new SqlCommand(strCmd, mySqlConn); mySqlCmd.ExecuteNonQuery(); Response.Write("<script>alert('OK!,导入数据成功!');history.go(-1);</script>"); } mySqlConn.Close(); } //} else throw new Exception("请选择导入表的路径"); } catch (Exception ex) { Response.Write("<script language='javascript'>alert('" + ex.Message + "');</script>"); } finally { System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { file.Delete(); } } } |