protected void readFromDB_Click(object sender, EventArgs e) { string strConn = ConfigurationManager.AppSettings["strConn"].ToString(); DataSet ds = new DataSet(); using (SqlConnection conn = new SqlConnection(strConn)) {
string sql = "select * from users"; SqlDataAdapter sda = new SqlDataAdapter(sql, conn); sda.Fill(ds, "users");//Fill方法会判断连接是否打开,没有则隐式打开,使用完后关闭 }
//将DS绑定到GridView GridView1.DataSource = ds.Tables["users"]; GridView1.DataBind(); }
protected void Import_Click(object sender, EventArgs e) { string filePath = ""; string getErrMsg = ""; DataSet excelDs = new DataSet();
if (FileUpload1.PostedFile.FileName == "") { Response.Write("<script language=javascript>alert('请选择要上传的文件!');</script>"); return; }
//从Excel读取数据 filePath = FileUpload1.PostedFile.FileName; string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";Data Source=" + filePath; OleDbConnection excelConn = new OleDbConnection(connString); OleDbDataAdapter ExcelDA = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConn);
try { ExcelDA.Fill(excelDs, "users"); } catch (Exception err) { Response.Write(err.Message); } finally { excelConn.Close(); excelConn = null; }
//将数据写入数据库 if (excelDs.Tables[0].Rows.Count != 0) { string sql = ""; string strConn = ConfigurationManager.AppSettings["strConn"]; SqlConnection sqlConn = new SqlConnection(strConn); sqlConn.Open();
try { for (int i = 0; i < excelDs.Tables[0].Rows.Count; i++) { sql = "insert into users(userID, userName, address) values('" + excelDs.Tables[0].Rows[i]["ID"].ToString() + "','" + excelDs.Tables[0].Rows[i]["用户名"].ToString() + "','" + excelDs.Tables[0].Rows[i]["地址"].ToString() + "')"; SqlCommand cmd = new SqlCommand(sql, sqlConn); cmd.ExecuteNonQuery(); } } catch (Exception ex) { getErrMsg = ex.Message.ToString(); Response.Write(ex.Message.ToString()); } finally { sqlConn.Close(); sqlConn = null; } }
//返回提示信息 if (getErrMsg == "" || getErrMsg == null) { Response.Write("<script language='Javascript'>alert('导入成功!')</script>"); return; } else { Response.Write("<script language='Javascript'>alert('导入失败!')</script>"); return; } }
|