我有关于导入到SQL Server的问题,方案是导入excel文件并计算导入的excel文件的第3列和第4列(生成第5列)中的值。在我的例子中,计算是在C#中,而不是在Excel中。然后导入到SQL Server(ASP.Net + C#)。知道怎么做吗?
这是我的代码(它仍然给我错误)
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";
}
}
答案 0 :(得分:0)
错误应该来自这一行
bulkInsert.WriteToServer(dr);
这种情况正在发生,因为您之前调用的DT.Load(dr)
已经遍历dr
并已将指针移动到结尾,之后您无法再次使用dr
DT.Load(dr); //<-- this line already looped through the dr. dr can't be used after this line
使用DT
代替dr
,因为您已通过调用DT
填充了所需数据DT.Load(dr)