How to read an excel and insert data into a table?

2

I wanted to send data from a file Excel to a table in Sql .

I've tried using bulkcopy.ColumnMappings.Add but you're giving me an error.

  

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 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();
 }
    
asked by anonymous 17.10.2017 / 13:37

0 answers