Arooran
Arooran

Reputation: 637

Selecting the Excel sheet used range using OLEDB Connection

Is there any way to select the Excel sheet used range via OLEDB Command object?

Because I have an Excel file that has 400 rows, but when I delete 200 rows and try to select the sheet again, it's selecting up to 400 rows again instead of selecting the 200 rows. This is the code which I've written to select the sheet:

oledbConn = new OleDbConnection(connectionString);
oledbCmd = new OleDbCommand("select * from [Sheet1$]", oledbConn);
oledbConn.Open();
oledbDr = oledbCmd.ExecuteReader();
    while(oledbDr.Read())
    {
}

Upvotes: 0

Views: 7367

Answers (2)

Try select DISTINCT * from [Sheet1$]

Upvotes: 0

mike
mike

Reputation: 550

Afaik you can do this in two ways:

First.

Write a simple SQL select in OleDBCommand. At the moment you are selecting all rows in the excel. Probably the fact that you deleted 200 rows from the document does not help since it still selects those empty rows.

Sample:

select * from [Sheet1$] WHERE ID <= 200

Second.

Load your entire data to DataTable and work on this programatically.

Sample:

DataTable xlsData = new DataTable();
List<string> result = new List<string>();
string query = string.Format("SELECT * FROM [{0}]", this.SheetName);
OleDbDataAdapter dbAdapter = new OleDbDataAdapter(query, dbConnection);
dbAdapter.Fill(xlsData);
foreach (DataColumn column in xlsData.Columns)
{
  result.Add(column.ColumnName);
}

Upvotes: 2

Related Questions