我想使用c#搜索excel文件以找到特定的文本拼写(ASSEMBLY)。我有这个小代码写的:
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”一词。如何继续搜索并显示所有结果,而不仅仅是第一个?
答案 0 :(得分:-1)
k = 1;
do {
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[k];
} while (k <= oWB.Worksheets.Count);