【问题标题】:Python docx - Multiple color in one linePython docx - 一行中的多种颜色
【发布时间】:2021-09-08 00:05:22
【问题描述】:

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

我创建了多个包含文本和变量的表格。 当行中有变量时,我将它们标记为: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)

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

【问题讨论】:

    标签: python colors fonts python-docx


    【解决方案1】:

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

    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.")
    

    【讨论】:

    • 你是一个救生员。不仅是你给我找到了答案。但你也帮助我了解 docx 段落是如何工作的。在此之前,如果我需要多个元素进入同一段落,我正在创建一个包含每个元素的字符串。然后用这个字符串添加一个段落。所以我可以修改我的段落的某些部分(如样式或对齐)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2014-06-20
    • 1970-01-01
    • 2022-10-16
    • 2015-11-04
    相关资源
    最近更新 更多