问题
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())
{
}
回答1:
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);
}
回答2:
Try select DISTINCT * from [Sheet1$]
来源:https://stackoverflow.com/questions/8927822/selecting-the-excel-sheet-used-range-using-oledb-connection