我有一个Web应用程序,可以将数据从Excel文件导入到Gridview。然后可以将来自GridView的数据保存到rowbasis上的SQL数据库(使用复选框)。但是我在导入具有与SQL数据库不同的列名的Excel文件时出现问题。可以这样做吗? 以下是将数据从excel文件导入GridView的代码(在按钮单击事件中)
DataTable dtExcel = new DataTable();
OleDbCommand command = new OleDbCommand("select * from Sheet1$]", oledbconn);
OleDbDataAdapter dr = new OleDbDataAdapter("select * from [Sheet1$]", oledbconn)
DataSet ds = new DataSet();
dr.Fill(ds, "Select");
DataTable dt = ds.Tables["Select"];
GridView1.DataSource = dt;
GridView1.DataBind();
lblresult.Text = "Record Uploaded";
我用来将数据保存到sql表的代码是 -
SqlConnection cn = new SqlConnection("Data Source=Deepesh;Initial Catalog=ExcelDB;Integrated Security=SSPI");
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gvr.FindControl("checkselect");
//Label lblid = (Label)gvr.FindControl("lblid");
Label lblname = (Label)gvr.FindControl("lblname");
Label lbllogin = (Label)gvr.FindControl("lbllogin");
Label lblemail = (Label)gvr.FindControl("lblemail");
DropDownList lbldesignation = (DropDownList)gvr.FindControl("DropDownList");
TextBox lbladdress = (TextBox)gvr.FindControl("TextBox2");
if (chk.Checked == true)
{
cn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Employee(Name,Login_Id,Email_Id,Designation,Address) VALUES(@lblname,@lbllogin,@lblemail,@lbldesignation,@lbladdress)", cn);
// command.Parameters.AddWithValue("lblid",Convert.ToInt32(lblid.ToString()));
command.Parameters.AddWithValue("@lblname", lblname.Text.ToString());
command.Parameters.AddWithValue("@lbllogin", lbllogin.Text.ToString());
command.Parameters.AddWithValue("@lblemail", lblemail.Text.ToString());
command.Parameters.AddWithValue("@lbldesignation", lbldesignation.Text.ToString());
command.Parameters.AddWithValue("@lbladdress", lbladdress.Text.ToString());
command.ExecuteNonQuery();
cn.Close();
}
lblresult.Text = "Data Saved";
}
}
}
答案 0 :(得分:0)
可以做到。我认为我们需要检查gridview控件的列数和属性。