正如标题所述,将excel文件导入我的数据库时显示错误。我似乎在代码中找不到任何错误。
这是我在控制器中的代码:
HttpPost:
[HttpPost]
public ActionResult ImportGrade(HttpPostedFileBase file)
{
string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
string filepath = "/excelfolder/" + filename;
file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));
InsertExceldata1(filepath, filename);
return View("Grade");
}
连接器:
private void ExcelConn(string filepath)
{
string constr = string.Format(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};
Extended Properties = ""Excel 12.0 Xml;HDR=YES""", filepath);
Econ = new OleDbConnection(constr);
}
将Excel保存到数据库:
private void InsertExceldata1(string filepath, string filename)
{
string fullpath = Server.MapPath("/excelfolder/") + filename;
ExcelConn(fullpath);
string query = string.Format("Select * from [{0}]", "Sheet1$");
OleDbCommand Ecom = new OleDbCommand(query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable dt = ds.Tables[0];
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "StudentGrade";
objbulk.ColumnMappings.Add("StudentNumber", "StudentNumber");
objbulk.ColumnMappings.Add("CourseName", "CourseName");
objbulk.ColumnMappings.Add("Midterm", "Midterm");
objbulk.ColumnMappings.Add("Finals", "Finals");
con.Open();
objbulk.WriteToServer(dt);
con.Close();
}
Excel数据:
错误:
System.Data.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理
其他信息:“ StudentNumber”列不允许 DBNull.Value。
如果有人可以帮助我,我将不胜感激。问候!