我用python和docx模块创建了一个word文档。我想要一些方法来更改整个文档的背景颜色,但我找不到任何方法。有什么想法吗?
from docx import Document
document = Document()
使用此方法。
-
首先创建两个 Word 文件。一个具有您喜欢的格式,一个完全空白。保存它们。
-
使用一些解压缩工具提取docx文件。
-
打开文件
settings.xml
并document.xml
并使用比较工具比较两个docx文件中的文件,例如Winmerge或Meld -
在
document.xml
寻找<w:background w:color="004586"/>
- 在
settings.xml
寻找<w:displayBackgroundShape/>
现在尝试使用上述方法设置字段。
如果这不起作用,您可以按照此处描述的 LibreOffice 文件的方法(以 XML 形式打开,修改或添加节点,保存、压缩(。
Joe 和 Post 引用使用 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')