title: OleDbDataReader Excel data to C#
body: <p>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 <code>System.IndexOutOfRangeException</code>. At the bottom, there is the code that I would like to have in case my current method is not good.</p>
  
  <p><strong>Excel table:</strong></p>
  
  <p><a href="https://i.stack.imgur.com/qLoPm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qLoPm.jpg" alt="enter image description here"></a></p>
  
  <p><strong>Code:</strong></p>
  
  <pre><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());
          }
      }           
  
  }
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <p>1
  2
  3
  4
  5
  6
  7
  8
  9
  10</p>
  
  <p><strong>I would like to have something like:</strong> (this doesn't work)</p>
  
  <pre><code>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());
          }
      }           
  
  }
  </code></pre>