5

How can I select specific columns from excel sheet rather than all columns

string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", txtPath.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];    
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
amer
  • 51
  • 1
  • 1
  • 2

3 Answers3

7

What about:

SELECT * FROM [Sheet1$B14:C20]

This should select cells B14 to C20.

Kev
  • 118,037
  • 53
  • 300
  • 385
1

This will sound trivial but this is what I understand from your question. Instead of SELECT * use SELECT [columnName1],[columnName2] FROM Sheet1.. Here columnName1 and columnName2 should be the headers of columns that you want to get from Excel Sheet.

emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
0

If you want to select the data before populating here is a good reference on advanced select statements. If you want to manipulate your data post populating your DataSet then here's how:

DataTable myTable = dataSet.Tables[0];

var myColumn = myTable.Columns["ColumnName"];

or

var myColumn = myTable.Columns[0];

To access a single field it would look something like this.

var field = myTable.Rows[0][myColumn];
jsmith
  • 7,198
  • 6
  • 42
  • 59
  • I need to specify the columns before filling the dataset – amer Aug 22 '11 at 17:06
  • @amer I have only done that through the Jet engine when knowing my Column Titles. I provided a link that I hope will help. – jsmith Aug 22 '11 at 17:12