基本上,您需要将整个 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());
}
请让我知道改进。