Enter text in font color in MS word using python-docx

I am trying to write text in an MS Word file using the python python-docx library. I looked at the python-docx font color documentation at this link and applied the same in my code, but so far without success.

Here is my code:

from docx import Document
from docx.shared import RGBColor
document = Document()
run = document.add_paragraph('some text').add_run()
font = run.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
p=document.add_paragraph('aaa')
document.save('demo1.docx')

The text in the word file 'demo.docx' is simply black.

I can not understand this, help will be greatly appreciated.

+5
source share
1 answer

I myself found the answer using python-docx docs,

Here is the correct code:

from docx import Document
from docx.shared import RGBColor
document = Document()
run = document.add_paragraph().add_run('some text')
font = run.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
p=document.add_paragraph('aaa')
document.save('demo1.docx')

"some text" is a parameter of the add_run () function, not the add_paragraph () function.

The above code gives the desired color.

+4

Source: https://habr.com/ru/post/1668510/


All Articles