简体   繁体   中英

Change color text in paragraph using OpenXML

I have a Word document lorem.docx with this content:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

[BLUE]

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

[/BLUE]

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

I need change the color of the specific paragrah between [BLUE] and [/BLUE]. I have this code:

string path = @"C:\Users\Kenneth\Desktop\lorem.docx";
using (WordprocessingDocument document = WordprocessingDocument.Open(path, true))
{
     DocumentFormat.OpenXml.Wordprocessing.Document doc = document.MainDocumentPart.Document;

     // Get and set the style properties of each content control
     foreach (var itm in elements)
     {
         try
         {
             List<Text> textparts = document.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().ToList();

             // CHANGE COLOR:
             foreach (RunProperties rp in list_runProperties)
             {
                 rp.Color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "cc0000" };
             }
          }
      }
}

But it change the color of the whole document. I need change the color of the text between BLUE tags.

How can I do this?

It looks like your code is just iterating through all RunProperties which is why they're all changing.

The basic structure of an OpenXML document is:

<Document>
    <Body>
        <Paragraph>
            <Run>
                <RunProperty>
                   <Text>

where the RunProperty will be a child of a Run. You need to go through each element looking for the Text that contains what you're looking for ("[BLUE]" in the example) and only apply the change to its parent Run.

This can be a bit tricky since Word won't necessarily place text in a single Text element and may split it across multiple but since this is a simpler case you can probably just look for the Text descendants as currently, compare it's InnerText with "[BLUE]" and change the RunProperty for that one. You might also then need to reset it to black on the following Run since I'm not sure if it will do it otherwise.

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