0

我正在研究 excel 中的搜索词突出显示。搜索词保存在 xml 文件中。下面的代码突出显示整个单元格,而不仅仅是突出显示特定的单词。

我哪里错了?我只需要突出显示单元格中的搜索词,而不是整个单元格(单元格中的所有单词)。

try
{
    string[] arr = XDocument.Load(@"C:\Users\273714\Desktop\Dictionary.xml").Descendants(nodeString).Select(element => element.Value).ToArray();

    string str;
    int rCnt = 0;
    int cCnt = 0;

    Excel.Worksheet xlWorkSheet1;
    Excel.Range range;
         xlWorkSheet1 = (Excel.Worksheet)doc1.Worksheets.get_Item(1);
    Excel.Range last = xlWorkSheet1.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
    range = xlWorkSheet1.get_Range("A1", last);
   // range = xlWorkSheet1.get_Range("A1", "A100");

    //Do your search thing here

    for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
    {
        for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
        {
            str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
            if (str == null)
            {
                Console.WriteLine("null");
            }
            else
            {
                str.Replace("\\", "");
                string[] words = str.Split(' ');
                foreach (string arrs in arr)

                {
                   foreach (string word in words)
                    {
                        if (word == arrs)
                        {
                            var cell = (range.Cells[rCnt, cCnt] as Excel.Range);

                            cell.Font.Bold = 1;
                            cell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                        }
                    }
                }
            }
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
4

1 回答 1

0

据此,单元格中的所有字母都会突出显示。我认为您只想突出显示您搜索的单元格中的文本。你可以按照这个

Excel.Range val = xlWorkSheet.Cells[18, "C"] as Excel.Range;
string match = "find";
string match2 = val.Value2.ToString();
int index=-1;
//Here apply  string  matching to find index of first letter of matching sub string 
// if the index is not -1  then do following      
            val.get_Characters(index, match.Length).Font.Color =System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
于 2013-09-12T08:53:55.400 回答