使用c#突出显示Docx中的文本

我需要在docx文件中突出显示一个句子,我有这个代码,并且它适用于许多文档,但是我注意到对于某些文档,文档中的文本是逐字设置的,而不是整个句子,我的意思是每个单词都带有它自己的Run,所以在搜索那个句子时,找不到它,因为它在docx中逐字逐句。 注意:我正在使用阿拉伯语文本。

private void HighLightText_userSentence(Paragraph paragraph, string text, string title, string author, decimal percentage, string _color) { string textOfRun = string.Empty; var runCollection = paragraph.Descendants(); Run runAfter = null; //find the run part which contains the characters foreach (Run run in runCollection) { if (run.GetFirstChild() != null) { textOfRun = run.GetFirstChild().Text.Trim(); if (textOfRun.Contains(text)) { //remove the character from thsi run part run.GetFirstChild().Text = textOfRun.Replace(text, ""); runAfter = run; break; } } } // create a new run with your customization font and the character as its text Run HighLightRun = new Run(); RunProperties runPro = new RunProperties(); RunFonts runFont = new RunFonts() { Ascii = "Curlz MT", HighAnsi = "Curlz MT" }; Bold bold = new Bold(); DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = _color }; DocumentFormat.OpenXml.Wordprocessing.FontSize fontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "22" }; FontSizeComplexScript fontSizeComplex = new FontSizeComplexScript() { Val = "24" }; Text runText = new Text() { Text = text }; //runPro.Append(runFont); runPro.Append(bold); runPro.Append(color); //runPro.Append(fontSize); // runPro.Append(fontSizeComplex); HighLightRun.Append(runPro); HighLightRun.Append(runText); //HighLightRun.AppendChild(new Break()); //HighLightRun.PrependChild(new Break()); //insert the new created run part paragraph.InsertBefore(HighLightRun, runAfter); } 

我最近使用了docX,并且遇到了搜索和高亮显示文本的问题。 我试着间接的方式。 它很简单,适用于大多数情况。 我使用replace语句来做。 这里搜索文本是您要突出显示的文本

  using (DocX doc = DocX.Load("d:\\Sample.docx")) { for (int i = 0; i < doc.Paragraphs.Count; i++) { foreach (var item in doc.Paragraphs[i]) { if (doc.Paragraphs[i] is Paragraph) { Paragraph sen = doc.Paragraphs[i] as Paragraph; Formatting form = new Formatting(); form.Highlight = Highlight.yellow; form.Bold = true; sen.ReplaceText(searchText, searchText, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase, form, null, MatchFormattingOptions.ExactMatch); } } } doc.Save(); }