突出显示Excel中的搜索词

时间:2013-09-12 06:56:50

标签: c# xml excel highlight

正在使用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);
}

1 个答案:

答案 0 :(得分: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);