c# 搜索 excel sheet 并验证文本框内容是否与单元格匹配

c# Search excel sheet and verify if textbox contents match cell

新手在这里寻求帮助。

我有这个有效的代码,但它只确认是否找到了文本框文本。

我一直在尝试调整它以确认在搜索 excel sheet 时文本框文本是否与 excel 单元格完全匹配。 请帮忙,因为我是新手,有点迷路了。

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(@"C:\pricefile.xlsx");
        Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets["Sheet1"];
        Excel.Range colRange = xlWorkSheet.Columns["A:A"];
        string searchString = textBox1.Text;
        Excel.Range resultRange = colRange.Find(
            What: searchString,
            LookIn: Excel.XlFindLookIn.xlValues,
            LookAt: Excel.XlLookAt.xlPart,
            SearchOrder: Excel.XlSearchOrder.xlByRows,
            SearchDirection: Excel.XlSearchDirection.xlNext
            );

        if (resultRange is null)
        {
            MessageBox.Show("Did not find " + searchString + " in Price File");
        }
        else
        {
            MessageBox.Show("Found " + searchString + " in Price File");
        }
        xlWorkBook.Close(false);
        xlApp.Quit();
    }

任何帮助都会很棒。 谢谢。

要获得字符串的精确匹配,您需要将 LookAt 参数设置为 Excel.XlLookAt.xlWhole。 参见:https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xllookat(v=office.14).aspx

如果要使搜索区分大小写(默认不区分大小写),还有一个 MatchCase 参数。 参见:https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.find(v=office.14).aspx