C# 搜索 Excel 工作簿
本文关键字:工作簿 Excel 搜索 | 更新日期: 2023-09-27 18:33:46
我想使用 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 文档多次出现"程序集"一词。如何继续搜索并显示所有结果,而不仅仅是第一个结果?
k = 1;
do {
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[k];
} while (k <= oWB.Worksheets.Count);