我想使用一种方法,我脱离了CodePlex,它从Excel导出数据到SQL表中。我做了一些小的代码调整,但我似乎仍然无法获取要导入的数据。有人看到我的语法有什么明显的错误吗?谢谢。C#导入Excel数据到SQL表
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select Name,EmployeeID from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlcmd.Connection.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
您必须更具体地了解您实际获得的行为。您是否尝试过使用调试器来完成此操作? –
我已经尝试过,但对编程来说是新的,而且对于断点来说并不是最好的。我在Excel中添加了一个连接,并在Main中添加了一个实际的方法,但在断开后我没有看到任何错误。当我运行代码时,控制台应用程序打开并在大约一秒后关闭,就好像它已经成功了一样,但是当我检查表时没有数据存在。 – AndrewC10
这看起来像是一次学习调试的机会:-)尝试创建自己的阅读器循环,以查看是否可以从源表中实际读取数据。手动将随机数据放在名称表中,看它是否至少被删除。只需验证整个过程的每一步。 –