使用 docx python 库,如何同时应用颜色和字体大小
Using docx python library, how to apply color and font size simultaneously
我正在使用 python docx 库写入 .docx 文件。我想预先指定一个特定句子的字体大小和颜色。我的问题是我无法同时进行。让我举例说明 -
from docx import Document
from docx.shared import Pt #Helps to specify font size
from docx.shared import RGBColor #Helps to specify font Color
document=Document() #Instantiation
p=document.add_heading(level=0)
p.add_run('I want this sentence colored red with fontsize=22').font.size=Pt(22) #Specifies fontsize 22
p.add_run('This line gets colored red').font.color.rgb=RGBColor(255,0,0) #Specifies RED color
document.save('path/file.docx')
结果:
我很清楚我将颜色 Red
设置为第二句,并且由于 Pt(22)
和 RGBColor(255,00)
之前有一个 =
所以我不能同时应用 fontsize
和 color
有没有办法同时应用这两个属性?
已编辑:我想要红色的行 I want this sentence colored red with fontsize=22
。
也许你可以做到这一点
document=Document()
p=document.add_heading(level=0)
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.size = Pt(22)
wp.font.color.rgb = RGBColor(255,0,0)
我正在使用 python docx 库写入 .docx 文件。我想预先指定一个特定句子的字体大小和颜色。我的问题是我无法同时进行。让我举例说明 -
from docx import Document
from docx.shared import Pt #Helps to specify font size
from docx.shared import RGBColor #Helps to specify font Color
document=Document() #Instantiation
p=document.add_heading(level=0)
p.add_run('I want this sentence colored red with fontsize=22').font.size=Pt(22) #Specifies fontsize 22
p.add_run('This line gets colored red').font.color.rgb=RGBColor(255,0,0) #Specifies RED color
document.save('path/file.docx')
结果:
我很清楚我将颜色 Red
设置为第二句,并且由于 Pt(22)
和 RGBColor(255,00)
之前有一个 =
所以我不能同时应用 fontsize
和 color
有没有办法同时应用这两个属性?
已编辑:我想要红色的行 I want this sentence colored red with fontsize=22
。
也许你可以做到这一点
document=Document()
p=document.add_heading(level=0)
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.size = Pt(22)
wp.font.color.rgb = RGBColor(255,0,0)