0

我有一个将数据从 Excel 文件导入到我的 Gridview 的 Web 应用程序。然后可以将 GridView 中的数据按行保存到 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";

    }
}

}

4

1 回答 1

0

可以办到。我认为我们需要检查gridview控件的列数和属性。

于 2013-08-22T07:17:39.367 回答