【问题标题】:I can't change the style of text in Word documents with Python-docx我无法使用 Python-docx 更改 Word 文档中的文本样式
【发布时间】:2014-12-12 19:01:56
【问题描述】:

我创建了一个包含文本的word文档

你好。你欠我 ${debt}。请尽快还给我。

Times New Roman 大小 12。文件名是 debtTemplate.docx。我想使用 python-docx 将 {debt} 替换为实际数字(1.20)。我尝试了以下代码:

from docx import Document

document = Document("debtTemplate.docx")
paragraphs = document.paragraphs

debt = "1.20"

paragraph = paragraphs[0]
text = paragraph.text
newText = text.format(debt=debt)
paragraph.clear()
paragraph.add_run(newText)

document.save("debt.docx")

这会生成一个包含所需文本的新文档,但 Calabri 字体大小为 11。我希望字体与原始字体相同:Times New Roman 大小为 12。

我知道您可以将样式变量添加到paragraph.add_run(),所以我尝试了,但没有任何效果。例如paragraph.add_run(newText,style="Strong") 甚至没有改变任何东西。

有人知道我能做什么吗?

编辑:这是我的代码的修改版本,我希望它可以工作,但没有。

from docx import Document

document = Document("debtTemplate.docx")
document.save("debt.docx")
paragraphs = document.paragraphs

debt = "1.20"

paragraph = paragraphs[0]
style = paragraph.style
text = paragraph.text
newText = text.format(debt=debt)
paragraph.clear()
paragraph.add_run(newText,style)
document.save("debt.docx")

【问题讨论】:

  • 有点晚了...你想把所有东西都做成 Times New Roman 和 12 号吗?

标签: python docx python-docx


【解决方案1】:

文档中的此页面应该可以帮助您了解样式无效的原因。这是一个非常简单的解决方法:http://python-docx.readthedocs.org/en/latest/user/styles.html

我喜欢你发现的其他几点:

  1. 使用 str.format() 方法进行占位符替换是进行轻量级文本替换的好方法。我必须将其添加到文档中,作为一种简单的自定义文档生成方法。

  2. 在段落的 XML 中,有一个名为 <w:defRPr> 的可选元素,Word 使用它来指示添加到段落中的任何新文本的默认格式,就像您在将插入点放置在段落的结尾。现在,python-docx 忽略了该元素。这就是为什么您将获得默认的 Calibri 11 而不是您开始使用的 Times New Roman 12。但是一个有用的功能可能是使用该元素(如果存在)将运行属性分配给在段落末尾添加的任何新运行。如果您想将其作为功能请求添加到 GitHub 跟踪器,我们将看看如何实现它。

【讨论】:

  • 您好,scanny,感谢您的回答。我在定义document 后立即添加了document.save("debt.docx")。我曾希望将 debtTemplate 的样式(Times New Roman 字体 12)因此保存在 styles.xml 中,以便我可以使用它。唉,它没有用。这是我修改后的完整代码:
  • 实际上代码并没有出现在 cmets 中,所以我将编辑我的原始帖子。
猜你喜欢
  • 2020-04-24
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
相关资源
最近更新 更多