我正在用c#编写一个Windows应用程序,并且在一种形式中我想以这种方式使用一个excel文件。
在用户在文本框中键入员工ID的表单中,我想搜索excel文件,并根据ID在其他一些文本框中显示员工的其他信息(名称文本框,姓氏文本框,状态文本框和食物计数文本框)
请告诉我如何从中检索信息。
public List <string>[] RetrieveColumnGeneral(Excel.Worksheet sheet,string FindWhat)
{
int columnCount = sheet.UsedRange.Columns.Count;
List<string>[] columnValue = new List<string>[columnCount];
Excel.Range rngResult = null;
Excel.Range rng = null;
int index = 0;
int rowCount = sheet.UsedRange.Rows.Count;
Excel.Range FindRange = null;
for (int columnIndex = 1; columnIndex <= sheet.UsedRange.Columns.Count;columnIndex++ )
{
FindRange = sheet.UsedRange.Columns[columnIndex] as Excel.Range;
FindRange.Select();
rngResult = FindRange.Find(What: FindWhat, LookIn: Excel.XlFindLookIn.xlValues,
LookAt: Excel.XlLookAt.xlPart, SearchOrder: Excel.XlSearchOrder.xlByRows);
if (rngResult != null)
{
columnValue[index] = new List<string>();
for (int rowIndex = 1; rowIndex <= sheet.UsedRange.Rows.Count;rowIndex++ )
{
rng = sheet.UsedRange[rowIndex, columnIndex] as Excel.Range;
if (rng.Value != null)
{
columnValue[index].Add(rng.Value.ToString());
}
}
index++;
}
}
Array.Resize ( ref columnValue , index);
return columnValue;
}
谢谢我找到了这段代码。你能告诉我这是否能解决我的问题吗?(也可以通过一些修改。)
答案 0 :(得分:0)
试试这个,
You have to passed Sheet object, but in below code SQL statement fire and get all records in DataSet object.
string sql = "SELECT * FROM [" + selectedWorksheetName + "]";
var adapter = new OleDbDataAdapter(sql, excelObject.Connection);
adapter.Fill(activityDataSet, "Results");
if (activityDataSet.Tables[0] != null)
{
//here you will check which data get based on your columns
}
答案 1 :(得分:0)
尝试这样的事情。
var ds = new DataSet();
var adapter = new OleDbDataAdapter("SELECT * FROM [" + newSheetName + "]", ConnectionString);
adapter.Fill(ds, newSheetName);
然后使用上面的数据集来过滤行。
DataRow dataRow = (from DataRow dr in ds.Tables[0].Rows where dr["Id"] == textbox.Text select dr).FirstOrDefault();
if(dataRow != null)
{
// Fill values from this dataRow
}
修改强>
// If excelsheet ends with .xls
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ExcelData\QB Accounts.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
// If excelsheet ends with .xlsx
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\ExcelData\CSENG01.xlsx;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";