Search code examples
c#sqlexceloledbdataadapter

Import Excel trough OleDbDataAdapter in C# With changing Column names


Hello well i try to import a Excel document into my DataGridView in C#. So far it worked but there is a Column with Data in it i need to 'sort'.

If this was simple i would do "WHERE test > 0" in the OleDbDataAdapter query.

But.. The name of the Column is changing with each document and i need to use it often. So far i got this :

    private void button1_Click(object sender, EventArgs e)
    {

        String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
        "Data Source=C:\\Users\\Test\\Desktop\\Test.xls;" +
        "Extended Properties=Excel 8.0;";

        DataSet ds = new DataSet();
        OleDbDataAdapter da = new OleDbDataAdapter
        ("SELECT * FROM [Test$]", strConn);

        da.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0].DefaultView;

    }

In the select i need to put a line witch state that the first 3 letters of the column is the same but the number that follow are not. Like:

QTA 12345, QTA 13213, QTA 92818.

Something like:

    OleDbDataAdapter da = new OleDbDataAdapter
        ("SELECT * FROM [Test$] WHERE [testColumn] > 0", strConn);

But then with the same first 3 letters and the last numbers who are random.

Can someone help me please?


Solution

  • I've tried some code and it works fine for me. Have a try:

    OleDbConnection oleDbConnection = new OleDbConnection(
      "Provider=Microsoft.Jet.OLEDB.4.0;" +
      "Data Source=D:\\Users\\name\\Desktop\\test.xls;" +
      "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
    oleDbConnection.Open();
    
    //Get columns
    DataTable dtColumns = oleDbConnection.GetSchema("Columns", new string[] { null, null, "Tabelle1$", null });
    List<string> columns = new List<string>();
    
    foreach (DataRow dr in dtColumns.Rows)
      columns.Add(dr[3].ToString());
    
    string colName = columns.Find(item => item.Substring(0,3) == "QTA");
    
    DataSet ds = new DataSet();
    OleDbDataAdapter da = new OleDbDataAdapter
      ("SELECT * FROM [Tabelle1$] WHERE [" + colName + "] > 0", oleDbConnection);
    da.Fill(ds);
    dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
    oleDbConnection.Close();
    

    Pay attention to changing the connection string to your needs.

    You can trim the code, using LINQ:

    string colName = (from DataRow dr in dtColumns.Rows where dr[3].ToString().Substring(0, 3) == "QTA" select dr[3].ToString()).ElementAt(0);