突出显示Word文档中的字符串

时间:2013-02-08 05:22:26

标签: c# asp.net aspose

我在ASP.NET网站(Web Forms,.NET 4.0)中工作 我有一个word文档,它是使用Aspose.Words创建的。现在我需要突出显示的某些字符串 word document.I需要一个函数来执行此操作。 像这样的东西,

private void Highlight(Document doc,String anyString,Color red)
{
    //Highlight all "anyString" in doc by red color
}

有人可以帮助我实现这个目标吗?

2 个答案:

答案 0 :(得分:3)

您可以使用Aspose为您执行此操作,这样您就可以避免Web服务器上的文字自动化(可能没有安装办公室)。大部分代码都基于Aspose documentation的示例。

设置以下课程:

 private class ReplaceEvaluatorFindAndHighlight : IReplacingCallback
    {
        /// <summary>
        /// This method is called by the Aspose.Words find and replace engine for each match.
        /// This method highlights the match string, even if it spans multiple runs.
        /// </summary>
        ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
        {
            // This is a Run node that contains either the beginning or the complete match.
            Node currentNode = e.MatchNode;

            // The first (and may be the only) run can contain text before the match, 
            // in this case it is necessary to split the run.
            if (e.MatchOffset > 0)
                currentNode = SplitRun((Run)currentNode, e.MatchOffset);

            // This array is used to store all nodes of the match for further highlighting.
            List<Node> runs = new List<Node>();

            // Find all runs that contain parts of the match string.
            int remainingLength = e.Match.Value.Length;
            while (
                (remainingLength > 0) &&
                (currentNode != null) &&
                (currentNode.GetText().Length <= remainingLength))
            {
                runs.Add(currentNode);
                remainingLength = remainingLength - currentNode.GetText().Length;

                // Select the next Run node. 
                // Have to loop because there could be other nodes such as BookmarkStart etc.
                do
                {
                    currentNode = currentNode.NextSibling;
                }
                while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
            }

            // Split the last run that contains the match if there is any text left.
            if ((currentNode != null) && (remainingLength > 0))
            {
                SplitRun((Run)currentNode, remainingLength);
                runs.Add(currentNode);
            }

            // Now highlight all runs in the sequence.
            foreach (Run run in runs)
                run.Font.HighlightColor = Color.Red;

            // Signal to the replace engine to do nothing because we have already done all what we wanted.
            return ReplaceAction.Skip;
        }

        /// <summary>
        /// Splits text of the specified run into two runs.
        /// Inserts the new run just after the specified run.
        /// </summary>
        private static Run SplitRun(Run run, int position)
        {
            Run afterRun = (Run)run.Clone(true);
            afterRun.Text = run.Text.Substring(position);
            run.Text = run.Text.Substring(0, position);
            run.ParentNode.InsertAfter(afterRun, run);
            return afterRun;
        }
    }

然后使用它:

Aspose.Words.Document doc = new Aspose.Words.Document(@"Z:\Temp\test.docx");

Regex reg = new Regex("anyString", RegexOptions.IgnoreCase);
doc.Range.Replace(reg, new ReplaceEvaluatorFindAndHighlight(), true);


doc.Save(@"Z:\Temp\newdoc.docx");

答案 1 :(得分:0)

您可以使用以下代码打开Word文档并突出显示搜索到的文本:

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

您必须使用以下语句添加对Microsoft.Office.Interop.Word的引用:

using Word = Microsoft.Office.Interop.Word;

如果你想做一个功能,那就修改它