简体   繁体   中英

How can i select specific columns from excel sheet in c#?

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];    

What about:

SELECT * FROM [Sheet1$B14:C20]

This should select cells B14 to C20 .

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 .

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM