2

I wanted to do a mapping of an excel file but with the columns in a certain way. As for example I have an exel file where the second column (of the excel file) has to be referenced there is 1 column of the sql database.

This is the Form I'm using: enter image description here

I already have the sql search done I just wanted to know how I can put in the combobox the name of the columns in the excel file.

This is the code I am using to search the excel file:

        using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
        {
            DataSet result;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
                IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
                reader.IsFirstRowAsColumnNames = true;
                result = reader.AsDataSet();
                comboBox1.Items.Clear();
                foreach (DataTable dt in result.Tables) comboBox1.Items.Add(dt.TableName);
                reader.Close();

                string ConecçãoDB = ConfigurationManager.ConnectionStrings["ConecçaoDB"].ConnectionString;
                string Table = ConfigurationManager.AppSettings["table"];

                string ssqltable = Table;

                string ssqlconnectionstring = ConecçãoDB;

                filename = ofd.FileName;
                MessageBox.Show(Convert.ToString(filename));
                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 conexao = new System.Data.OleDb.OleDbConnection(connectionString);
                var sql = "SELECT * FROM [" + comboBox1.SelectedText + "$]";
                string sclearsql = "delete from " + ssqltable;
            }
        }
Pedro Azevedo
  • 228
  • 4
  • 12

1 Answers1

2

Updating my answer based on your latest comment as I misunderstood what you need.

You need to access Excel object model and after that you will have full and easy control over Excel data.

For a solid and simple answer refer to :

Microsoft Interop: Excel Column Names

When using the suggested code make sure you add the following reference to your code:

using Microsoft.Office.Interop.Excel;

Remember the provided answer there puts the column names in a generic list of strings.

After that you have to bind it to combo box:

BindingSource bs = new BindingSource();
bs.DataSource=columnNames ;
comboBox1.DataSource = bs;
S Nash
  • 2,363
  • 3
  • 34
  • 64