我正在尝试将数据从Excel文件插入到Mysql DB中。它的工作原理但问题是,它只插入一列。我需要插入Excel文件中的所有列
这是我的代码
protected void add_Click(object sender, EventArgs e)
{
if (importfile.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + importfile.FileName)));
importfile.PostedFile.SaveAs(path);
OleDbConnection oleConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 8.0;");
OleDbCommand oleCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oleConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCmd);
DataSet ds = new DataSet();
oleAdapter.Fill(ds);
DataTable Dt = new DataTable();
Dt = ds.Tables[0];
string userId = (string)(Session["id"]);
string groupName = groupname.Text.ToString();
try {
for (int i = 0; i < Dt.Rows.Count; i++)
{
DataRow row = Dt.Rows[i];
int columnCount = Dt.Columns.Count;
string[] columns = new string[columnCount];
for (int j = 0; j < columnCount; j++)
{
columns[j] = row[j].ToString();
}
conn.Open();
string sql = "INSERT INTO contacts(user_id, idNum, contact_name, contact_number, group_name)";
sql += "VALUES('" + userId + "','" + columns[0] + "','" + columns[1] + "','" + columns[2] + "','" + groupName + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
string message = "Success!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "alert", sb.ToString());
Response.Redirect("viewgroups.aspx");
conn.Close();
}
}
}
catch (Exception)
{
string message = "Failed!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "alert", sb.ToString());
}
这很难过。请帮忙。感谢