import docx
from docx.api import Document
from docx.shared import RGBColor
if condition:
paragraph = row[2].add_paragraph('Different Text') # Not Blue
else:
blue_paragraph = row[2].add_paragraph('X')
font = blue_paragraph.style.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
The above code is not only making my entire row[2]
blue, it is making the entire document blue. How can I set only the 'X' text blue?
In this line:
font = blue_paragraph.style.font
You're selecting the font of what is probably the Normal
style, and then setting it to blue in the following line. This explains why the whole document is turning blue; Normal
is the default style for all paragraphs in the document.
You either need to create a new style that is blue and apply that to the paragraphs in question, or set the font of the runs of the target text directly.
So something like this would work, but be less optimal in some ways than using a style:
blue_paragraph = row[2].add_paragraph("X")
for run in blue_paragraph.runs:
run.font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
This page in the python-docx
documentation describes Word styles in a way you might find helpful.
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html