使用python docx在MS word中以特定字体颜色编写文本

使用python docx在MS word中以特定字体颜色编写文本,python,python-docx,Python,Python Docx,我正在尝试使用python库python docx在MS Word文件中编写文本。 我已经阅读了pythondocx字体颜色的文档,并在代码中应用了相同的字体颜色,但到目前为止还没有成功 这是我的密码: from docx import Document from docx.shared import RGBColor document = Document() run = document.add_paragraph('some text').add_run() font = run.font

我正在尝试使用python库python docx在MS Word文件中编写文本。 我已经阅读了pythondocx字体颜色的文档,并在代码中应用了相同的字体颜色,但到目前为止还没有成功

这是我的密码:

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')
word文件“demo.docx”中的文本仅为黑色


我无法解决这个问题,非常感谢您的帮助。

我自己使用python docx文档找到了答案

以下是正确的代码:

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”是add_run()函数的参数,而不是add_段落()函数的参数


上面的代码给出了所需的颜色。

font.color.rgb=RGBColor.from_string('FF0000')

这将便于构造RGBColor