0

I am using Open XML SDK to highlight a specific word inside a docx file but I not able to do that, after an extensive research I did the following I tried to open the document and then edit the color of the word and save it again, but I get no thing saved while I found the document last edit time with now date.

What is wrong with that code?

void HighLightWord(string documentUrl, string word)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentUrl, true))
    {
        var body = wordDoc.MainDocumentPart.Document.Body;
        var paras = body.Elements<Paragraph>();
        DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color();

        foreach (var para in paras)
        {
            foreach (var run in para.Elements<Run>())
            {
                foreach (var text in run.Elements<Text>())
                {
                    if (text.Text.Contains(word))
                    {
                        color.Val = "365F91";
                        run.Append(color);
                        wordDoc.MainDocumentPart.Document.Save();
                        return;
                    }
                }
            }
        }
        wordDoc.Close(); // close the template file
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
Amr Ramadan
  • 1,259
  • 5
  • 18
  • 29
  • Possible duplicate of [highlighting text in Docx using c#](http://stackoverflow.com/questions/26131230/highlighting-text-in-docx-using-c-sharp) – MethodMan Nov 16 '15 at 19:20
  • can you tell us what's wrong with the code.. you have written it... can you step through the code and pinpoint where the issues is happening.? – MethodMan Nov 16 '15 at 19:22

1 Answers1

1

Create a simple document in the Word application with the formatting you need. Save and close. Open the document in the Open XML SDK Productivity Tool. That will generate the code required to create the document. Then you can compare your code to that of the Tool's.

FWIW any kind of formatting is a child element of the RunProperties, so appending a color directly to the Run cannot work. In addition, you need to create an object for the kind of formatting (it's not clear from your description whether you want to change the text color or apply highlight formatting). That is what's appended to the RunProperties. It's also important that your code first check whether RunProperties are available for the Run. If not, that first needs to be created before anything can be appended to it.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43