我收到错误
The given ColumnMapping does not match up with any column in the source or destination
使用以下代码
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 区分大小写,我复制了相同的列名,但出现了相同的错误..
有什么办法可以解决这个问题吗?
最佳答案
使用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);
当我尝试时,我的所有测试行都已添加到数据库中。
关于c# - 使用 C# 将 Excel 导入 SQL Server 时出现 "The given ColumnMapping does not match up with any column in the source or destination",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091057/