将多个不同的 Excel 工作表合并到一个 SQL 表中

发布于 2024-09-28 06:25:05 字数 4135 浏览 0 评论 0原文

我有很多 Excel 工作表,其中的列略有不同,我想将所有这些工作表(一次一个)导入到一个 SQL 表中。我举一个例子:

假设我编写了所需的程序并将其命名为 Excel2sql 转换器。因此,Excel2sql 需要一个 Excel 工作表并使用该 Excel 工作表的数据创建一个数据库表,例如,假设我有以下 Excel 工作表:

Excel_Sheet_1
-----------------------------
FirstName MiddleName LastName
John      A.         Smith

当我运行 Excel2sql (Excel_Sheet_1) 时,应使用以下数据为我创建一个数据库表它:

FirstName MiddleName LastName
John      A.         Smith

现在,当我使用以下 Excel 表再次运行我的程序时:

Excel_Sheet_2
-----------------------------
LastName FirstName MiddleName 
wolf     Kerry         M.

我应该得到以下更新的数据库表:

FirstName MiddleName LastName
John      A.         Smith
Kerry     M.         wolf 

请注意,它将 Excel 表 2 的数据添加到已经存在的数据库表中。 它在 db 的列和 Excel 表 2 的列之间进行了某种映射,以适当地附加数据。

现在,如果我使用以下 Excel 表再次运行我的程序:

Sheet 3
--------
PhoneNumber LastName MiddleName FirstName
232-232     Lame        K.       Phoebe

我应该得到以下数据库表:

FirstName MiddleName LastName  PhoneNumber
John      A.         Smith       Null
Kerry     M.         wolf        Null
Phoebe    K.         Lame        232-232

我希望代码动态地执行此操作,我的意思是,任何人都可以使用我的代码,给它一个 Excel 表作为输入,我的然后代码将为他创建一个 sql 数据表,每次用户给他一个 Excel 工作表时,它都应该更新已经创建的 sql 表。

拜托,我真的需要我能得到的所有帮助。我对此很陌生。我编写了一段原始代码,只需将一张 Excel 工作表上传到已有的数据表中。 (这不是我想要的,但我必须从某个地方开始)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void insertdata_Click(object sender, EventArgs e)
    {
        //-----------------connection to excel=--------------------------
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("example.xls") + ";Extended Properties=Excel 8.0");
        try
        {
            //-----------------Commad to get all columns---------------------
            OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);

            //-----------------open  the connection-----------------------
            oconn.Open();

              //-----------------execute the command ----------------------
            OleDbDataReader odr = ocmd.ExecuteReader();
            string fname = "";
            string lname = "";
            string mobnum = "";

              //-----------------read from the datareader-------------------
            while (odr.Read())
            {

                   //-----------------insert into the db table ------------------ 
                insertdataintosql(fname, lname, mobnum);
            }
            oconn.Close();
        }
        catch (DataException ee)
        {
            lblmsg.Text = ee.Message;
          }
        finally
        {
            lblmsg.Text = "Data Inserted Sucessfully";
        }
    }

    public void insertdataintosql(string fname, string lname, string mobnum)
    {
        //-----------------connection to sql database----------------

        SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;AttachDbFileName=|DataDirectory|exceltosql.mdf;Trusted_Connection=yes");


        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "insert into dbtable(fname,lname,mobnum) values(@fname,@lname,@mobnum)";
        cmd.Parameters.Add("@fname", SqlDbType.NVarChar).Value = fname;
        cmd.Parameters.Add("@lname", SqlDbType.NVarChar).Value = lname;
        cmd.Parameters.Add("@mobnum", SqlDbType.NVarChar).Value = mobnum;

        cmd.CommandType = CommandType.Text;
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }

}

我写的代码再次不是我想要的,你能帮我修改它以获得我想要的要求吗!

先感谢您 :)

I have a lot of excel sheets which columns are slightly different, i want to import all of these sheets (one at a time) into ONE SQL TABLE. I'll give an example :

Say ive written the required program and called it Excel2sql converter. So Excel2sql takes an excel sheet and create a database table with the data of that excel sheet, For example say i have the following excel sheet:

Excel_Sheet_1
-----------------------------
FirstName MiddleName LastName
John      A.         Smith

when i run Excel2sql (Excel_Sheet_1), a database table should be CREATED for me with the following data in it:

FirstName MiddleName LastName
John      A.         Smith

Now, when i run my program again with the following excel sheet:

Excel_Sheet_2
-----------------------------
LastName FirstName MiddleName 
wolf     Kerry         M.

i should get the following UPDATED db table:

FirstName MiddleName LastName
John      A.         Smith
Kerry     M.         wolf 

Notice that it added the data of excel sheet 2, into the already existing database table.
It did some kind of mapping between the columns of db and the columns of the excel sheet 2 to append the data appropriately.

Now, if i run my program again with the following excel sheet:

Sheet 3
--------
PhoneNumber LastName MiddleName FirstName
232-232     Lame        K.       Phoebe

i should get the following db table:

FirstName MiddleName LastName  PhoneNumber
John      A.         Smith       Null
Kerry     M.         wolf        Null
Phoebe    K.         Lame        232-232

I want the code to do this dynamically, i mean, anybody can use my code, give it an excel sheet as an input, my code will then CREATE for him an sql data table and each time a user gives him an excel sheet, it should UPDATED the already created sql table.

Please i really need all the help i can get. Im very new at this. I wrote a primitive code that simply uploads one excel sheet into an ALREADY existing datatable. (which is not what i want , but i had to start somewhere)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void insertdata_Click(object sender, EventArgs e)
    {
        //-----------------connection to excel=--------------------------
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("example.xls") + ";Extended Properties=Excel 8.0");
        try
        {
            //-----------------Commad to get all columns---------------------
            OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);

            //-----------------open  the connection-----------------------
            oconn.Open();

              //-----------------execute the command ----------------------
            OleDbDataReader odr = ocmd.ExecuteReader();
            string fname = "";
            string lname = "";
            string mobnum = "";

              //-----------------read from the datareader-------------------
            while (odr.Read())
            {

                   //-----------------insert into the db table ------------------ 
                insertdataintosql(fname, lname, mobnum);
            }
            oconn.Close();
        }
        catch (DataException ee)
        {
            lblmsg.Text = ee.Message;
          }
        finally
        {
            lblmsg.Text = "Data Inserted Sucessfully";
        }
    }

    public void insertdataintosql(string fname, string lname, string mobnum)
    {
        //-----------------connection to sql database----------------

        SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;AttachDbFileName=|DataDirectory|exceltosql.mdf;Trusted_Connection=yes");


        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "insert into dbtable(fname,lname,mobnum) values(@fname,@lname,@mobnum)";
        cmd.Parameters.Add("@fname", SqlDbType.NVarChar).Value = fname;
        cmd.Parameters.Add("@lname", SqlDbType.NVarChar).Value = lname;
        cmd.Parameters.Add("@mobnum", SqlDbType.NVarChar).Value = mobnum;

        cmd.CommandType = CommandType.Text;
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }

}

Again the code ive written is NOT what i want, can you please help me modify it to get the requirements i want!

Thank you in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月依秋水 2024-10-05 06:25:05

首先,如果您创建一个只包含 RowID 列的最小表,您的生活会稍微轻松一些。这样,您就可以避免必须在第一次传递时创建表的边缘情况。或者,您可以在第一遍中执行此操作,并使用 ALTER TABLE ... 引入第一组列,与任何其他遍相同。

下一步是查询 sysobjects 和 syscolumns 中的元数据,以确定哪些列尚不存在,并使用 ALTER TABLE ... 来添加它们。

第三步是读取标题行并使用它来构建 SQL 语句。使用@_1、@_2作为参数名称,以避免在最后一步中记住这些名称。

最后,迭代剩余的行。对于每一行,将单元格绑定到相应的参数,然后执行该语句。

First off, you'll make life slightly easier on yourself if you create a minimal table containing, say, just a RowID column. This way, you avoid the edge case of having to create the table on the first pass. Or, you could do this on the first pass, and introduce the first group of columns using ALTER TABLE ..., the same as any other pass.

The next step is to query the metadata in sysobjects and syscolumns to figure which columns aren't already there, and add them with ALTER TABLE ....

The third step is to read the heading row and use it to build the SQL statement. Use @_1, @_2 as parameter names to avoid having to remember the names in the final step.

Finally, iterate over the remaining rows. For each row, binding the cells to the corresponding paremeter and then execute the statement.

国粹 2024-10-05 06:25:05

首先非常感谢您的回复!

让我看看我是否明白你所说的:

如果sheet1包含ABCD列,当我运行代码时,我将有一个包含ABCD列的sql表,

那么如果我有另一个包含ABCDE列的表,我会这样做步骤

0:获取现有表的所有列名称(在本例中为 ABCD)

步骤 1:从 Excel 工作表(ABCDE)读取标题行

步骤 2-a) 比较步骤 0 和步骤 1 的结果
步骤 2- b) 获取我的 sql 表中缺少的列名称并将它们添加到其中 (
在本例中为 E 列,因此将其添加到表中后,我的 sql 表将具有
ABCDE 列,

但当你说以下内容时我不明白你的意思:

#
第三步是读取标题行并使用它来构建 SQL 语句。使用@_1、@_2作为参数名称,以避免在最后一步中记住这些名称。

最后,迭代剩余的行。对于每一行,将单元格绑定到相应的参数,然后执行该语句。
#
我再次非常感谢你的帮助:):)

First of all, thank you so much for replying !

let me see if i got what you said:

if sheet1 that has the columns A B C D , when i run the code, i will have an sql table that has the columns A B C D

then if i have another sheet that has the columns A B C D E, i will do the following :

step 0 : get all columns names of my existing table ( in this case A B C D)

step 1 : read the heading rows from excel sheet ( A B C D E )

step 2- a) compare the result of step 0 and step 1
step 2- b) get the columns names that are missing from my sql table and add them to it (
in this case column E) so after adding it to the table, my sql table will have
the columns A B C D E

but i didnt understand what you meant when u said the following:

#
The third step is to read the heading row and use it to build the SQL statement. Use @_1, @_2 as parameter names to avoid having to remember the names in the final step.

Finally, iterate over the remaining rows. For each row, binding the cells to the corresponding paremeter and then execute the statement.
#
again i really appreciate ur help :):)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文