如何以编程方式突出显示word文档中括号之间的单词

时间:2016-10-07 03:21:35

标签: c# ms-word office-interop

我正在尝试在word文档中的括号中突出显示文本,但我的代码仅突出显示括号。这是我的代码:

private void button5_Click(object sender, EventArgs e)
{
    object textf = "(";
    object texs = ")";
    object color = Color.Cyan;
    object oMissing = System.Reflection.Missing.Value;
    acWord.Application.Selection.Find.ClearFormatting();

    acWord.Application.Selection.Find.HitHighlight(ref textf, ref color, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

} 

1 个答案:

答案 0 :(得分:1)

应该是这样的。

private void btnFind_Click(object sender, EventArgs e)
{
    object fileName = "xxxxx"; //The filepath goes here
    string textToFind = "xxxxx"; //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;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message);
    }
}

您也可以试试这个。

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\References.docx");

            TextSelection[] text = document.FindAllString("forming", false, true);
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FindHighlight.docx");
        }
    }
}