2
我想用C#查找文本(组装)的特定刺痛。我这个小码所著搜索一个excel文件:C#通过Excel工作簿中搜索
private void button1_Click(object sender, EventArgs e)
{
string File_name = "C:\\test.xls";
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oWB;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
try
{
object missing = System.Reflection.Missing.Value;
oWB = oXL.Workbooks.Open(File_name, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing);
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[3];
Microsoft.Office.Interop.Excel.Range oRng = GetSpecifiedRange("ASSEMBLY", oSheet);
if (oRng != null)
{
MessageBox.Show("Text found, position is Row:" + oRng.Row + " and column:" + oRng.Column);
}
else
{
MessageBox.Show("Text is not found");
}
oWB.Close(false, missing, missing);
oSheet = null;
oWB = null;
oXL.Quit();
}
catch (Exception ex)
{
}
}
private Microsoft.Office.Interop.Excel.Range GetSpecifiedRange(string matchStr, Microsoft.Office.Interop.Excel.Worksheet objWs)
{
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Range currentFind = null;
Microsoft.Office.Interop.Excel.Range firstFind = null;
currentFind = objWs.get_Range("A1", "AM100").Find(matchStr, missing,
Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues,
Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, missing, missing);
return currentFind;
}
该工程确定,就可以找到工作簿中给定的字符串。但是,该工作簿有很多工作表,现在我只搜索一个(表3)。如何搜索整个工作簿?
另外,这个excel文件有很多次“ASSEMBLY”这个词。如何继续搜索并显示所有结果,而不仅仅是第一个?
您专门询问表3 ..所以这就是你正在寻找 – Rob
要搜索每个表,迭代他们:'的foreach(Excel.Worksheet片oWB.Worksheets){...}'。要继续搜索致电'.FindNext' –
希望你的帖子能为你的问题实现的答案...谢谢 – sam