System.ArgumentException: 列“Class”不属于表 [StudentSheet.xls$]。
在做通过按钮将excel导入到数据库时,出现 System.ArgumentException: 列“Class”不属于表 [StudentSheet.xls$]。 在 System.Data.DataRow.GetDataColumn(String columnName) 在 System.Data.DataRow.get_Item(String columnName) 在 Book.Web.Mudules.HealthTeacher.StudentList.btnLoadUp_Click(Object sender, EventArgs e)位置 E:\Web\Web\Mudules\HealthTeacher\StudentList.aspx.cs:行号 263 问题 ,麻烦大家帮忙看看 非常急的
代码:
string filepath = FileUpload1.FileName;
string savePath = Server.MapPath("~/ExcelTemp/" + filepath);//Server.MapPath 获得虚拟服务器相对路径
if (savePath.Substring(savePath.LastIndexOf(".") + 1) != "xls")
{
Response.Write("请选择正确的文件");
return;
}
SqlConnection co = new SqlConnection();
co.ConnectionString = "server=WIN-CLU0FATHSEK;database=12110125117;Integrated Security=SSPI;";
try
{
co.Open();
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + savePath + ";Extended Properties='Excel 8.0'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn);
myCommand.SelectCommand.Prepare();
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + filepath + "$]");
conn.Dispose();
myCommand.Dispose();
int c = ds.Tables[0].Rows.Count;
if (c == 0)
{
Response.Write("没有满足条件的记录");
return;
}
for (int i = 0; i < c; i++)
{
SqlCommand cmm = new SqlCommand(" INSERT INTO StudentSheet ([Class],[Code],[Name],[Sex],[Birth],[Political],[Campus],[Education],[Address],[TelNo])" + " VALUES ( " +
"" + ds.Tables[0].Rows[i]["Class"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Code"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Name"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Sex"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Birth"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Political"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Campus"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Education"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["Address"].ToString() + ", " +
"" + ds.Tables[0].Rows[i]["TelNo"].ToString() + "," + " )"
, co
);
cmm.ExecuteNonQuery();
cmm = new SqlCommand(
"select @@identity from StudentSheet"
, co
);
object newid = cmm.ExecuteScalar();
cmm.Dispose();
}
Response.Write("成功导入!");
return;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
return;
}
finally
{
if (co.State == System.Data.ConnectionState.Open)
co.Close();
}
}