C# 在导入到SQL Server之前计算Excel值
我在导入到SQL Server时遇到问题,场景是导入excel文件并计算第3列和第4列中的值,生成导入的excel文件的第5列。在我的例子中,计算是用C语言进行的,而不是用excel。然后导入到SQL Server ASP.Net+C。你知道怎么做吗 这是我的代码,它仍然给我错误C# 在导入到SQL Server之前计算Excel值,c#,asp.net,excel,import,calculated-columns,C#,Asp.net,Excel,Import,Calculated Columns,我在导入到SQL Server时遇到问题,场景是导入excel文件并计算第3列和第4列中的值,生成导入的excel文件的第5列。在我的例子中,计算是用C语言进行的,而不是用excel。然后导入到SQL Server ASP.Net+C。你知道怎么做吗 这是我的代码,它仍然给我错误 protected void btnImport_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { strin
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
if (Extension == ".xlsx")
{
string path = string.Concat((Server.MapPath("~/tampung/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
//make connection to excel workBook
using (OleDbConnection oledbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbcon);
OleDbDataAdapter ObjAdapter1 = new OleDbDataAdapter(cmd);
oledbcon.Open();
using (DbDataReader dr = cmd.ExecuteReader())
{
DataTable DT = new DataTable();
DT.Load(dr);
for (int i = 0; i < DT.Rows.Count; i++)
{
string Year = DT.Rows[i][0].ToString();
string StudentName = DT.Rows[i][1].ToString();
string Semester = DT.Rows[i][2].ToString();
decimal Value1 = Convert.ToDecimal(DT.Rows[i][3]);
decimal Value2 = Convert.ToDecimal(DT.Rows[i][4]);
decimal AverageValue = Convert.ToDecimal((Value1 + Value2) / 2);
}
string conString = @"Data Source=PETRELLI;Initial Catalog=demo;Integrated Security=True";
SqlBulkCopy bulkInsert = new SqlBulkCopy(conString);
bulkInsert.DestinationTableName = "student";
bulkInsert.WriteToServer(dr);
oledbcon.Close();
Array.ForEach(Directory.GetFiles(Server.MapPath("~/temp/")), File.Delete);
Label1.Text = "Succeeded";
}
}
}
else
{
Label1.Text = "Hi, it's error";
}
}
else
{
Label1.Text = "Please choose the right file excel";
}
}
错误应该来自这一行
bulkInsert.WriteToServer(dr);
之所以会发生这种情况,是因为您前面调用的DT.Loaddr已经在dr中循环,并且已经将指针移到了末尾,之后就不能再使用dr了
解决方案
使用DT而不是dr,因为通过调用DT.Loaddr,您已经用所需数据填充了DT。我们需要知道您得到了什么错误。错误是这样说的,先生:当读卡器关闭时调用FieldCount的尝试无效。谢谢@codingbiz,不管怎样,它工作得很好,您是否要更正我的代码,因为虽然它成功导入到SQL Server,但我在SQL Server中得到的平均值为NULL,提前感谢:-
DT.Load(dr); //<-- this line already looped through the dr. dr can't be used after this line