Selecting the Excel sheet used range using OLEDB Connection

自闭症网瘾萝莉.ら 提交于 2019-12-08 12:25:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!