突出显示忽略c#中word文档中的个案的文本

时间:2013-10-23 08:04:44

标签: c# ms-word highlight

使用以下代码可以突出显示搜索文本。但如果搜索文本是“也”,那么“也”不会突出显示。如何忽略案件。

 foreach (Word.Range w in doc.Words)
                            {

                                for (int i = 1; i < xmlnode.Count; i++)
                                {

                                    XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
                                    object text = xmlnode[i].FirstChild.InnerText;

                                    if (w.Text.Trim() == text.ToString())
                                    {
                                        w.Font.Bold = 1;
                                        w.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                                    }
                                }
                            }
                        }

2 个答案:

答案 0 :(得分:1)

       // int counter = 0;
        object readOnly = true;
        System.IO.StreamReader file =
         new System.IO.StreamReader(@"C:\Users\noor\Desktop\HIGH LIGHTER\Sample.txt");
        object matchWholeWord = true;
        //string textToFind  = "to";
        //string my = System.IO.File.ReadAllText(@"C:\Users\noor\Desktop\HIGH LIGHTER\Sample.txt");
        //var textToFind = my ;
       // textBox1.Text = textToFind.ToString ();
        while ((line = file.ReadLine()) != null)
        {

            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;
            doc = word.Documents.Open(ref fileName,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing);
            string ReadValue = string.Empty;
            // Activate the document
            doc.Activate();

            /* foreach (Word.Range tmpRange in doc.StoryRanges)
             {
                 ReadValue += tmpRange.Text;
             }
         */
            foreach (Word.Range docRange in doc.Words)
                try
                {

                    if (docRange.Text.Trim().Equals(line, StringComparison.CurrentCulture) == false )
                    {
                        docRange.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                        docRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                }
        }
           // counter++;


        file.Close();

    }

答案 1 :(得分:0)

您可以使用字符串比较方法:

if(String.Compare(w.Text.Trim(), text.ToString(), true) == 0)