我已經無數遍了我的代碼,並希望有人可以幫助我看到我不知道的東西。我試圖從Excel中將數據從VS2010中的多列拖到SQL表中,但是當我嘗試上載數據時,出現錯誤「無法找到列8」。我沒有看到第8欄和其他任何欄目都沒有錯。還有誰?謝謝!Excel到SQL代碼:找不到列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;
}
}
數據集中第8列的數據是否存在?你是否已經通過調試器進行了檢查? – 2012-04-05 22:44:38
是的,在8列單元格之一中有數據,我已經設置爲接受SQL中的nvarchar(MAX)。調試器通過param.Value = DtSet.Tables [0] .Rows [i] [j]處的for(int j = 0,j <13; j ++)節捕獲8次。 – Sarah 2012-04-09 15:38:42