2

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

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

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

4

2 回答 2

3

您可以使用 Aspose 为您执行此操作,因此您可以避免 Web 服务器上的单词自动化(可能没有安装 Office)。大部分代码都基于 Aspose文档中的示例。

设置以下类:

 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");
于 2013-02-08T05:51:52.300 回答
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;

如果你想做一个函数,然后修改它

于 2013-02-08T05:28:50.093 回答