我必须使用值将excel文件插入表中。应通过下拉列值获取列的ID。其余的列值已通过Excel工作表插入。问题是,我编写了代码,但是没有将值插入到表中。 请参阅代码供您参考: -
protected void btnImport_Click(object sender, EventArgs e)
{
string name;
string storename;
string address;
string city;
int Id;
DataTable dt = new DataTable();
foreach (DataRow row in dt.Rows)
{
name = row["Merchant_Name"].ToString();
storename = row["Store_Name"].ToString();
address = row["Store_Address"].ToString();
city = row["City"].ToString();
Id = int.Parse(row["CategoryId"].ToString());
this.InsertRows(Id, name, storename, address, city);
}
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath(FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
Response.Write("<script>alert('File uploaded successfully');</script>");
}
}
private void InsertRows(int Id, string name, string storename, string address, string city)
{
string sSourceConstr1 = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""");
string sSourceConstr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""");
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
string constrng = ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constrng))
{
using (SqlCommand cmd = new SqlCommand(@"Insert Into MerchantDataTable values (@CategoryId, @MerchantName, @StoreName, @StoreAddress, @City)", conn))
{
cmd.Parameters.AddWithValue("@CategoryId", Id);
cmd.Parameters.AddWithValue("@MerchantName", name);
cmd.Parameters.AddWithValue("@StoreName", storename);
cmd.Parameters.AddWithValue("@StoreAddress", address);
cmd.Parameters.AddWithValue("@City", city);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}