【问题标题】:"The given ColumnMapping does not match up with any column in the source or destination" while importing Excel into SQL Server using C#使用 C# 将 Excel 导入 SQL Server 时,“给定的 ColumnMapping 与源或目标中的任何列都不匹配”
【发布时间】:2017-03-29 10:31:46
【问题描述】:

我收到一个错误

给定的 ColumnMapping 与源或目标中的任何列都不匹配

使用以下代码

private void button1_Click_1(object sender, EventArgs e)
{
    of1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

    if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK)
    {
        imagepath = of1.FileName; //file path
        textBox1.Text = imagepath.ToString();
    }
}

private void loadbtn_Click(object sender, EventArgs e)
{
    string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
    string myexceldataquery = "select * from ["+ ssqltable + "$]";

    try
    {
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+imagepath+";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
        string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";

        OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
        oconn.Open();

        OleDbDataReader dr = oledbcmd.ExecuteReader();

        SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
        bulkcopy.DestinationTableName = ssqltable;

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

        oconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

    /* DisplayingData DD = new DisplayingData();
    DD.Show();*/
}

我认为 SQL Server 区分大小写,我复制了相同的列名但同样的错误..

有没有办法解决这个问题?

【问题讨论】:

    标签: c# sql-server excel


    【解决方案1】:

    像这样使用SqlBulkCopy.ColumnMapping

    for (int i = 0; i < dr.FieldCount; i++) {
        bulkcopy.ColumnMappings.Add(i, i);
    }
    

    根据您的图片,我刚刚创建了一个测试表和一个测试文件。它对我来说很好,但只会添加第一行数据。

    也许您应该使用DataTable 并再试一次:

    DataTable dt = new DataTable();
    dt.Load(oledbcmd.ExecuteReader());
    SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
    bulkcopy.DestinationTableName = ssqltable;
    for(int i = 0; i < dt.Columns.Count; i++){
        bulkcopy.ColumnMappings.Add(i,i);
    }
    bulkcopy.WriteToServer(dt);
    

    当我这样尝试时,我的所有测试行都已添加到数据库中。

    【讨论】:

    • 在while语句中?
    • @AmrKamal:不,在 while 循环之前。您只需要进行一次列映射。
    • 当我把这个循环放在里面 for 工作但只添加了一列.. 然后我把它放在外面之前 while .. 显示相同的错误
    • 仍然只添加了第一列
    • @AmrKamal 在这里抓着稻草,但您确定您在 DataReader 中拥有 excel 文件中的所有列,而不仅仅是包含所有数据的一列吗?
    猜你喜欢
    • 2019-02-07
    • 2015-03-28
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多