2
I wanted to send data from a file Excel
for a table on Sql
.
I tried using the bulkcopy.ColumnMappings.Add
but you’re making a mistake.
System.Invalidoperationexception The Given Columnname does not match up with any column in the source or Destination
This is the code I use to send the data to sql:
string ConecçãoDB = ConfigurationManager.ConnectionStrings["ConecçaoDB"].ConnectionString;
string Table = ConfigurationManager.AppSettings["table"];
string ssqltable = Table;
string ssqlconnectionstring = ConecçãoDB;
string sclearsql = "delete from " + ssqltable;
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
var sql = "SELECT * FROM [" + comboBox1.Text + "$]";
MessageBox.Show(sql);
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
MessageBox.Show(sql);
OleDbConnection oledbconn = new OleDbConnection(connectionString);
OleDbCommand oledbcmd = new OleDbCommand(sql, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read()) {
bulkcopy.ColumnMappings.Add("TransDate", comboBox2.Text);
bulkcopy.ColumnMappings.Add("TransTime", comboBox3.Text);
bulkcopy.ColumnMappings.Add("CardNo", comboBox4.Text);
bulkcopy.ColumnMappings.Add("VoucherNo", comboBox5.Text);
bulkcopy.ColumnMappings.Add("Quantity", comboBox6.Text);
bulkcopy.ColumnMappings.Add("TransactionValue", comboBox7.Text);
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
button2.Enabled = true;
oledbconn.Close();
}
Adds error in @Pedro question.
– Marconi
@Marconi I’ll add already sorry
– Pedro Azevedo
@Marconi I’ve already added
– Pedro Azevedo
Do you want to read excel and insert the data into a specific table? @Pedro
– Marconi
@Marconi yes, I want to insert data from a specific excel columns within a specific sql table
– Pedro Azevedo
@Pedroazevedo, you need to select only the columns that will be used in the import, as well as respect the display order of the attributes.
– Leandro Angelo