我已经多次查看我的代码,希望有人可以帮助我看到我没有看到的东西。我正在尝试将数据从 Excel 提取到 VS2010 中具有多列的 SQL 表中,但是当我尝试上传数据时,出现错误“无法找到第 8 列”。我认为第 8 列和其他任何列都没有问题。还有谁?谢谢!
protected void Button1_Click(object sender, EventArgs e)
{
//make local copy
string sheetname = "Sheet1";
string path = Server.MapPath("~/Import.xls");
//connect to local Excel
try
{
FileUpload.SaveAs(path);
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand; //check sheet name
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + sheetname + "$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
SqlConnection curConnection = new SqlConnection(@"Data Source=1tc-Techcomm2;Initial Catalog=EventManagement;Integrated Security=True");
curConnection.Open();
SqlCommand curCommand;
SqlParameter param;
string str;
for (int i = 0; i < DtSet.Tables[0].Rows.Count; i++)
{
if (DtSet.Tables[0].Rows[i][1] == DBNull.Value)
continue;
curCommand = curConnection.CreateCommand();
curCommand.CommandText = @"Insert into TestSP (SessionHead_Title, SessionHead_Type, SessionHead_Description, SessionHead_Confirmed, SessionHead_Presenter, SessionHead_Champion, SessionHead_Objective, SessionHead_Notes, SessionHead_Schedule, SessionHead_Equipment, SessionHead_Hardware, SessionHead_CDA) Values (@a,@b,@c,@d,@e,@f,@g,@h,@i,@j,@k,@l,@m)";
for (int j = 0; j < 13; j++)
{
param = new SqlParameter();
str = "@";
str += (char)('a' + j);
param.ParameterName = str;
param.SqlDbType = SqlDbType.VarChar;
param.Value = DtSet.Tables[0].Rows[i][j];//This is where it errors out at after 8 times through
curCommand.Parameters.Add(param);
}
Label1.Text = "THE EXCEL DATE HAS SUCCESSFULLY BEEN SENT TO THE DATABASE";
int Event_Id = curCommand.ExecuteNonQuery();
}
MyConnection.Close();
curConnection.Close();
}
catch (Exception ex)
{
//Response.Write(ex.ToString());
Label1.Text = ex.Message;
}
}