【发布时间】:2020-06-18 11:40:07
【问题描述】:
我使用 python 和 docx 模块创建了一个 word 文档。我想要一些方法来更改整个文档的背景颜色,但我找不到任何方法。有什么想法吗?
from docx import Document
document = Document()
【问题讨论】:
标签: python colors python-docx
我使用 python 和 docx 模块创建了一个 word 文档。我想要一些方法来更改整个文档的背景颜色,但我找不到任何方法。有什么想法吗?
from docx import Document
document = Document()
【问题讨论】:
标签: python colors python-docx
首先创建两个 Word 文件。一种具有您喜欢的格式,一种完全为空。保存它们。
使用解压工具解压 docx 文件。
打开文件 settings.xml 和 document.xml 并使用差异工具比较两个 docx 文件中的文件,例如Winmerge 或 Meld
在document.xml中寻找<w:background w:color="004586"/>
settings.xml 中查找<w:displayBackgroundShape/>
现在尝试使用上述方法设置字段。
如果这不起作用,您可以按照 here 描述的方法处理 LibreOffice 文件(以 XML 格式打开、修改或添加节点、保存、压缩)。
【讨论】:
Joe 和Post Referenced 使用python-docx 对方法的详细解释。
import docx
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
doc = docx.Document()
doc.add_paragraph().add_run("Sample Text")
# Now Add below children to root xml tree
# create xml element using OxmlElement
shd = OxmlElement('w:background')
# Add attributes to the xml element
shd.set(qn('w:color'), '0D0D0D') #black color
shd.set(qn('w:themeColor'), 'text1')
shd.set(qn('w:themeTint'), 'F2')
# Add background element at the start of Document.xml using below
doc.element.insert(0,shd)
# Add displayBackgroundShape element to setting.xml
shd1 = OxmlElement('w:displayBackgroundShape')
doc.settings.element.insert(0,shd1)
# Save to file
doc.save('sample.docx')
【讨论】: