将Excel数据传输到具有不同列的SQL表中

时间:2016-12-21 20:34:06

标签: c# mysql excel

我希望用户一次使用C#WinForms应用程序将数据从Excel文件传输到SQL。 Excel文件由类似的列组成,因此可能缺少一些新的列或列。行数据会有所不同。

例如:

Excel文件1:名称,城市状态
Excel文件2:名称,城市,邮编 Excel文件3:名称,城市,县

在我现有的SQL表中,我有列:姓名,城市,人口,学校

如何将具有相似列名的新Excel文件插入现有SQL数据库?

到目前为止,我的想法是将新的Excel文件数据复制到临时表中,然后将其插入到现有的SQL表中。问题是,我不知道如何编写C#代码(或SQL查询),这些代码将插入比现有SQL表更多或更少列的新Excel数据。

3 个答案:

答案 0 :(得分:1)

为此目的,您需要No-SQL,如果您需要输入不属于表的列,那么如果您使用c#alter table,则sql不是一个好的选择,那么请注意后果。如果您确定前面所有可能的列名称,请在开始插入

之前尝试更改表格

答案 1 :(得分: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。我认为你可以通过这种方式更好地控制整个过程。

答案 2 :(得分:0)

如果您正在阅读此问题,那么我对其他问题的回答可能对您有所帮助(只需创建一个类来处理每一行信息,处理excel文件并执行批量插入,如此处所述):

Bulk insert is not working properly in Azure SQL Server

我希望它有所帮助。