2017-04-17 61 views
0

我努力嘗試,我只是無法承受最後一件事來結束我的申請。試圖用Interop.Word突出顯示完整的短語

我有一些短語作爲字符串存儲,例如「Something is just」。 現在我的程序將突出顯示所有「東西是正義的」,但也包括Word .docx文本中的所有「東西」,全部「是」以及全部「正義」。

我不知道如何使人們有可能,因爲現在我用我的文檔用文字分開。我不知道我是否應該使用其他的foreach類型,或者可能只有一個Range的方法可以幫助我解決這個問題。

這裏是我的代碼:

for (int i = 0; i < keyList.Count; i++) 
{ 
    foreach (Range range in doc.Words) 
    { 
     if (keyList[i].Contains(range.Text.Trim())) 
     { 
      range.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow; 
     }  
    } 
} 

鍵列表有三個詞串。 感謝您的幫助!

+0

http://stackoverflow.com/a/41364583/3060520 –

+0

的[我怎樣寫大膽的文字到Word文檔編程不加粗整個文檔?](可能的複製http://stackoverflow.com /問題/ 11564073 /怎麼辦,我寫粗體文本到一個字的文檔,編程,無需-加粗-的) – krillgar

+0

那不解決我的問題:( – Starynowy

回答

0

此解決方案基於使用Word's Range.Find object在文檔文本中查找短語的位置並設置任何找到的項目的HighlightColorIndex屬性。

public static void WordHighliter(Word.Document doc, IEnumerable<string> phrases, Word.WdColorIndex color) 
      { 
      Word.Range rng = doc.Content; 
      foreach (string phrase in phrases) 
       { 
       rng = doc.Content; 
       Word.Find find = rng.Find; 

       find.ClearFormatting(); 
       find.Text = phrase; 
       find.Forward = true; 
       find.Wrap = Word.WdFindWrap.wdFindStop; 
       find.Format = false; 
       find.MatchCase = false; 
       find.MatchWholeWord = true; 
       find.MatchWildcards = false; 
       find.MatchSoundsLike = false; 
       find.MatchAllWordForms = false; 
       find.MatchByte = true; 

       while (find.Execute()) 
        { 
        Int32 start = rng.Start; 
        // ensure that phrase does not start within another word 
        if (rng.Start == rng.Words[1].Start) 
         { 
         rng.HighlightColorIndex = Word.WdColorIndex.wdYellow; 
         } 
        } 
       } 

      } 
+0

因爲它真的有效謝謝!; ) – Starynowy