ExcelからSQLテーブルにデータをエクスポートするCodePlexのメソッドを使用しようとしています。マイナーなコード調整を行ったことがありますが、データをインポートすることができないようです。誰も私の構文で何かが間違って見えるのですか?ありがとう。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接続に1つ追加し、メインで実際のメソッドに1つ追加しましたが、壊れた後にカーソルを移動するとエラーは表示されません。私はコードを実行すると、コンソールアプリケーションが開き、約2秒後に正常終了したように閉じますが、テーブルをチェックするとデータは存在しません。 – AndrewC10
これはデバッグを学ぶ機会のように見えます:-)独自のリーダーループを作成して、実際にソーステーブルからデータを読み取ることができるかどうかを確認してください。手動でランダムなデータを 'Name'テーブルに入れて、少なくとも削除されているかどうか確認します。全体のプロセスの各ステップを検証するだけです。 –