2016-12-21 2 views
-3

C#WinFormsアプリケーションを使用して、ExcelファイルからSQLにデータを一度に1つずつ転送します。 Excelファイルは同様の列で構成されているため、新しい列または列がない場合があります。行データは変化します。異なる列のSQLテーブルにExcelデータを転送する

エクセルファイル1:名、都市国家
エクセルファイル2:たとえば

名前、市

郡:名、市は、
Excelが3ファイルジップ名前、都市、人口、学校

私は新しいExcelを挿入するにはどうすればよい:私の既存のSQLテーブルで

は、私が列を持っています既存のSQLデータベースに類似の列名を持つファイル

私の考えは、これまでの一時テーブルに新しいExcelファイルのデータをコピーして、既存のSQLテーブルにそれを挿入することです。問題は、既存のSQLテーブルより多かれ少なかれ新しいExcelデータを挿入するC#コード(またはSQLクエリ)の記述方法がわかりません。

答えて

1

この目的のためにNo-SQLが必要です。テーブルの一部ではない列を入力する必要がある場合はsqlは良いオプションではない場合は、#をalter tableに設定してください。あなたが前に可能なすべての列名について確実であるなら、あなたは

0

を挿入開始する前に、これはあまりにも難しいことshould'tあなたのテーブルを変更してみてください。 ExcelからSQL Serverのステージングテーブルテーブルにデータをエクスポートします。 C#コードはこのように見えるかもしれません。

public void importdatafromexcel(string excelfilepath) 
{ 
    //declare variables - edit these based on your particular situation 
    string ssqltable = "tdatamigrationtable"; 
    // 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 student,rollno,course 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;\""; 
     string ssqlconnectionstring = "server=mydatabaseservername;user 
     id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false"; 
     //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); 
     sqlconn.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; 
     while (dr.read()) 
     { 
      bulkcopy.writetoserver(dr); 
     } 

     oledbconn.close(); 
    } 
    catch (exception ex) 
    { 
     //handle exception 
    } 
} 

次にSQL Serverで、ステージングテーブルから最終の本番テーブルにデータを移動します。あなたのSQLは、このように見えるかもしれません。

insert into production 
select ... 
from staging 
where not exists 
(
    select 1 from staging 
    where staging.key = production.key 
) 

これは私の.02です。私はあなたがそのようにプロセス全体をより詳細に制御できると思います。

0

あなたがこの質問を読んでいる場合、この他の質問に対する私の答えは、(単にインクルードファイルをエクセル、プロセスを各行の情報を処理するためのクラスを作成し、そこに説明したように一括挿入を行う)あなたのために役立つかもしれない:

Bulk insert is not working properly in Azure SQL Server

私はそれが役に立てば幸い。

関連する問題