首页 > 解决方案 > Python docx - 一行中的多种颜色

问题描述

我目前正在使用 python docx 库生成一个 word 文件。

我创建了多个包含文本和变量的表格。当行中有变量时,我将它们标记为:<Variable_name>var

我需要将分隔符 <>var 的颜色更改为红色以突出显示它。

我认为我发现的关于文本颜色的唯一方法是:

p=document.add_paragraph()
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.color.rgb = RGBColor(255,0,0)

但它适用于所有段落,而不是特定部分。

标签: pythoncolorsfontspython-docx

解决方案


字符级格式(“字体”特征)在运行级控制。运行是共享相同字符级格式的字符序列。因此,如果您想在正常格式的段落中“运行”红色字符,则需要运行三个;一前一红一后。

paragraph = document.add_paragraph()
paragraph.add_run("The part before the red bit ")
run = paragraph.add_run("the red bit")
run.font ... # --- make the font of this run red ---
paragraph.add_run(" the part after the red bit.")

推荐阅读