如何以编程方式突出显示Word文档中括号之间的单词 [英] How to programmatically highlight word between parentheses in word document

查看:155
本文介绍了如何以编程方式突出显示Word文档中括号之间的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图突出显示Word文档中括号之间的文本,但是我的代码仅突出显示括号.这是我的代码:

I'm trying to highlight text between parentheses in a word document, but my code highlights only the parentheses. Here is my code:

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);

} 

推荐答案

应该是这样的.

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");
        }
    }
}

这篇关于如何以编程方式突出显示Word文档中括号之间的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆