2016-12-21 46 views
-3

我希望用戶一次使用C#WinForms應用程序一個文件將數據從Excel文件傳輸到SQL中。 Excel文件由相似的列組成,因此可能會出現一些新的列或列。行數據會有所不同。將Excel數據傳輸到具有不同列的SQL表中

例如:

Excel文件1:名,市州
Excel文件2:名稱,城市,郵編
Excel文件3:名稱,市,縣

在我現有的SQL表中,我有列:名稱,城市,人口,學校

如何插入新的Excel具有相似列名的文件放入現有的SQL數據庫中?

我到目前爲止的想法是將新的Excel文件數據複製到臨時表中,然後將其插入到現有的SQL表中。問題是,我不知道如何編寫C#代碼(或SQL查詢),這些代碼會插入比現有SQL表更多或更少列的新Excel數據。

回答

1

您需要非SQL用於此目的,如果您需要輸入尚未包含在表中的列,那麼如果您使用c#alter table,那麼sql不是一個好選擇,那麼請小心後果。如果您確信前面列出了所有可能的列名,請在開始插入之前嘗試更改您的表格

0

這應該不會太難。將您的數據從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。我想你會對這個過程有更多的控制權。

相關問題