【问题标题】:Write text in particular font color in MS word using python-docx使用 python-docx 在 MS word 中以特定字体颜色编写文本
【发布时间】:2017-06-18 03:49:52
【问题描述】:

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

这是我的代码:

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 python-docx


    【解决方案1】:

    我自己使用 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_paragraph() 函数的参数。

    上面的代码给出了想要的颜色。

    【讨论】:

      【解决方案2】:

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

      这对于构造 RGBColor 会很方便。

      【讨论】:

        【解决方案3】:

        RGBColor

        from docx import Document
        from docx.shared import RGBColor
        
        document = Document()
        paragraph = document.add_paragraph()
        run = paragraph.add_run('Red ')
        run.font.color.rgb = RGBColor(255, 0, 0)
        run = paragraph.add_run('Green ')
        run.font.color.rgb = RGBColor(0x00, 0xFF, 0x00)
        run = paragraph.add_run('Blue')
        run.font.color.rgb = RGBColor.from_string('0000FF')
        document.save('test.docx')
        

        【讨论】:

          猜你喜欢
          • 2019-04-19
          • 2023-01-14
          • 1970-01-01
          • 1970-01-01
          • 2014-01-08
          • 2020-04-10
          • 2022-09-24
          • 2019-02-01
          • 1970-01-01
          相关资源
          最近更新 更多