简体   繁体   中英

OpenXML C#: Change color of a word in wordprocessing

I want to change the color of a word. I am adding color in runproperties but instead of changing color of single word it change the color of whole line. see the code.

void AppendStyle(string document, string word, string col)
    {
        try
        {
            using (WordprocessingDocument wordDoc =
                    WordprocessingDocument.Open(document, true)) //Open file from path
            {
                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 = col;
                                run.AppendChild(color);
                                return;
                            }

                        }
                    }
                }

                wordDoc.Close(); // close the template file

            }

What Word does under the covers when you color only a part of a sentence is that it splits the sentence into multiple runs. You need to do the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM