我正在尝试将excel数据批量复制到SQL,但是数据不会复制,程序也不会抛出错误。 帮我指出做错了什么。
这是我的代码段
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
openFileDialog.ShowDialog();
if (!string.IsNullOrEmpty(openFileDialog.FileName))
{
string ssqltable = "Student";
string myexceldataquery = "select Name,DOB,Email from [Sheet1$]";
try
{
//Excel connection string
string Econn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog.FileName + ";Extended Properties=Excel 12.0;";
//Sql connection string
string Sconn = "Data Source=.;Initial Catalog=db_Test;Integrated Security=True";
SqlConnection sqlconn = new SqlConnection(Sconn);
sqlconn.Open();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(Econn);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(Sconn);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
}
答案 0 :(得分:0)
您在docs
中有一个完整的示例因此,我删除了sqlconn.close()行和循环while (dr.Read())
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
openFileDialog.ShowDialog();
if (!string.IsNullOrEmpty(openFileDialog.FileName))
{
string ssqltable = "Student";
string myexceldataquery = "select Name,DOB,Email from [Sheet1$]";
try
{
//Excel connection string
string Econn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog.FileName + ";Extended Properties=Excel 12.0;";
//Sql connection string
string Sconn = "Data Source=.;Initial Catalog=db_Test;Integrated Security=True";
using (SqlConnection sqlconn = new SqlConnection(Sconn))
{
sqlconn.Open();
//sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(Econn);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(Sconn);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
}
}
finally
{
dr.Close();
oledbconn.Close();
}