私は何度も自分のコードを調べてきましたが、誰かが私が知らないものを見るのを手伝ってくれることを願っています. VS2010 で複数の列を持つ SQL テーブルに Excel からデータを取得しようとしていますが、データをアップロードしようとすると、「列 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;
}
}