简体   繁体   English

OpenXML C#:在文字处理中更改文字的颜色

[英]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. 我在runproperties中添加了颜色,但没有更改单个单词的颜色,而是更改了整个行的颜色。 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. 当您仅对句子的一部分进行着色时,Word在幕后所做的就是将句子分成多个部分。 You need to do the same thing. 您需要做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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