在MS-Word文档中查找多个字符串并突出显示这些字符串

假设我必须在MS-Word文档中搜索多个字符串。 我想将多个关键字传递给word api,我需要api将通过MS-word打开该doc或docx文件,如果在我提供的ms-word文件中找到,则突出显示这些单词。 在这里,我得到了ms-word文件中突出显示单词的示例代码,但我找到的例程可能不会突出显示多个单词。 另一个问题我注意到,当它突出显示文件并打开然后它工作正常,但当我关闭ms字时,它要求保存更改。 我明白这个例程会修改文件以制作我不想要的高光。 我希望该例程将突出显示但不会修改doc文件….有没有办法做到这一点。 请指导。 谢谢

using Word = Microsoft.Office.Interop.Word; private void btnFind_Click(object sender, EventArgs e) { object fileName = "audi.doc"; //The filepath goes here string textToFind = "test1,test2,test3"; //The text to find goes here Word.Application word = new Word.Application(); Word.Document doc = new Word.Document(); object missing = System.Type.Missing; try { 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); doc.Activate(); foreach (Word.Range docRange in doc.Words) { if(docRange.Text.Trim().Equals(textToFind, StringComparison.CurrentCultureIgnoreCase)) { docRange.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow; docRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite; } } System.Diagnostics.Process.Start(fileName.ToString()); } catch (Exception ex) { MessageBox.Show("Error : " + ex.Message); } } 

您可以使用Range.Find属性 。

下面的代码打开文档以供只读使用,并在不更改文档的情况下选择要查找的单词的所有匹配项。

以下是一些代码:

  private static void HighlightText() { object fileName = "C:\\1.doc"; object textToFind = "test1"; object readOnly = true; Word.Application word = new Word.Application(); Word.Document doc = new Word.Document(); object missing = Type.Missing; try { doc = word.Documents.Open(ref fileName, ref missing, ref readOnly, 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); doc.Activate(); object matchPhrase = false; object matchCase = false; object matchPrefix = false; object matchSuffix = false; object matchWholeWord = false; object matchWildcards = false; object matchSoundsLike = false; object matchAllWordForms = false; object matchByte = false; object ignoreSpace = false; object ignorePunct = false; object highlightedColor = Word.WdColor.wdColorGreen; object textColor = Word.WdColor.wdColorLightOrange; Word.Range range = doc.Range(); bool highlighted = range.Find.HitHighlight(textToFind, highlightedColor, textColor, matchCase, matchWholeWord, matchPrefix, matchSuffix, matchPhrase, matchWildcards, matchSoundsLike, matchAllWordForms, matchByte, false, false, false, false, false, ignoreSpace, ignorePunct, false); System.Diagnostics.Process.Start(fileName.ToString()); } catch (Exception ex) { Console.WriteLine("Error : " + ex.Message); Console.ReadKey(true); } }