我想使用一種方法,我脫離了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
這看起來像是一次學習調試的機會:-)嘗試創建自己的閱讀器循環,以查看是否可以從源表中實際讀取數據。手動將隨機數據放在名稱表中,看它是否至少被刪除。只需驗證整個過程的每一步。 –