Search code examples
c#exceloledbdatareader

OleDbDataReader Excel data to C#


I would like to read data from an Excel table. At the moment, I select all of the data and then I select the part that I need. I'm wondering if this is a good approach, given that there will be about 1000 part numbers in the data file. If there is a better/more efficient way, what would that be? I tried directly selecting the correct column from the Excel table, but I got either the wrong output or the error System.IndexOutOfRangeException. At the bottom, there is the code that I would like to have in case my current method is not good.

Excel table:

enter image description here

Code:

using (OleDbConnection connection = new OleDbConnection(strConn))
{
    connection.Open();
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);

    string partnumber = "Part1"; // this value will change depending on the operator's choice.

    using (OleDbDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            Debug.WriteLine(rdr[partnumber].ToString());
        }
    }           

}

Output:

1 2 3 4 5 6 7 8 9 10

I would like to have something like: (this doesn't work)

using (OleDbConnection connection = new OleDbConnection(strConn))
{
    connection.Open();
    OleDbCommand cmd = new OleDbCommand("SELECT [@partNumber] FROM [Sheet1$]", connection);

    string partnumber = "Part1";

    cmd.Parameters.AddWithValue("@partNumber", partnumber);

    using (OleDbDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            Debug.WriteLine(rdr[xxx].ToString());
        }
    }           

}

Solution

  • If you have a column name and you need the column data, you can modify your code as follows:

    string columnName = "335610";
    OleDbCommand cmd = new OleDbCommand($"SELECT [{columnName}] FROM [Sheet1$]", connection);
    
    using (OleDbDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            Debug.WriteLine(rdr.GetValue(0).ToString());
        }
    }