2016-12-04 8 views
-3

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 
      } 
     } 
+0

あなたが実際に行っている動作について、より具体的に説明する必要があります。あなたはこれをデバッガでステップ実行しようとしましたか? –

+0

私は試しましたが、プログラミングには新しく、ブレークポイントでは最高のものではありません。 Excel接続に1つ追加し、メインで実際のメソッドに1つ追加しましたが、壊れた後にカーソルを移動するとエラーは表示されません。私はコードを実行すると、コンソールアプリケーションが開き、約2秒後に正常終了したように閉じますが、テーブルをチェックするとデータは存在しません。 – AndrewC10

+0

これはデバッグを学ぶ機会のように見えます:-)独自のリーダーループを作成して、実際にソーステーブルからデータを読み取ることができるかどうかを確認してください。手動でランダムなデータを 'Name'テーブルに入れて、少なくとも削除されているかどうか確認します。全体のプロセスの各ステップを検証するだけです。 –

答えて

1

問題はここにある:

while (dr.Read()) 
{ 
    bulkcopy.WriteToServer(dr); 
} 

あなたは結果の上に1対1を反復している場合while (dr.Read())ブロックが有用です。

しかし、結果を反復しているのはあなたではありません。一括コピー操作で反復処理を実行する必要があります。

単にあなたのために働く必要があり

bulkcopy.WriteToServer(dr); 
+0

ありがとうございます。上記のコードに示されているように、私はwhile文をコメントアウトし、バルクコピーコマンドを移動しました。まだインポートしたくないようです。私は接続文字列の中の何かを心配しています。 db名はTestDBで、テーブルはNameです。助けてくれてありがとう。 – AndrewC10

0

これと交換してください。

private void SaveFileToDatabase(string filePath) 
{ 
    String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; 

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); 
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
    { 
     //Create OleDbCommand to fetch data from Excel 
     using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection)) 
     { 
      excelConnection.Open(); 
      using (OleDbDataReader dReader = cmd.ExecuteReader()) 
      { 
       using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) 
       { 
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "Excel_table"; 
        sqlBulk.WriteToServer(dReader); 
       } 
      } 
     } 
    } 
} 


private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl) 
{ 


    string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName); 

    fileUploadControl.SaveAs(filePath); 

    return filePath; 

} 

詳細については、以下のリンクを参照してください。

https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh

http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/

あなたが言うことができるように、あなたが何をしたいのか行うには多くの方法があります。

関連する問題