基本上你需要將整個excel文件讀取到一個數據表,然後搜索數據表。
請原諒我,因爲我在LINQ中的知識有限。
// You can change C:\Members.xlsx to any valid path
// where the file is located.
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
Data Source=C:\Members.xlsx;Extended
FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
Properties=""Excel 12.0;HDR=YES;""";
// if you don't want to show the header row (first row) in the grid
// use 'HDR=NO' in the string
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open(); // this will open an Excel file
OleDbCommand dbCommand = new OleDbCommand(strSQL,excelConnection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);
// create data table
DataTable dTable = new DataTable();
dataAdapter.Fill(dTable);
// bind the datasource
dataBingingSrc.DataSource = dTable;
// assign the dataBindingSrc to the DataGridView
dgvExcelList.DataSource = dataBingingSrc;
// dispose used objects
dTable.Dispose() dataAdapter.Dispose(); dbCommand.Dispose(); excelConnection.Close(); excelConnection.Dispose();
然後,您可以按照您的要求搜索dTable。示例搜索如下:
string strExpr = null;
strSearch = "Name LIKE 'Pet%'";
DataRow[] Rows = null;
Rows = dTable.Select(strSearch);
for (i = 0; i <= Rows.GetUpperBound(0); i++) {
MessageBox.Show(Row(i)(0).ToString());
}
請讓我知道改進。
你只是想搜索excel並顯示消息框?或者你也想編輯任何值? – pordi
我想搜索excel文檔中的單詞(僅在名稱字段中),用戶在文本框中給出的文本...如果它存在意味着顯示消息.. – GOPI
@GOPI ..我已經添加了答案。請檢查並讓我知道這是否回答您的查詢.. – pordi