我正在使用python-docx从模板生成word文档,我需要更新文档的封面、页眉和页脚部分中嵌入的一些字段。
我找遍了所有地方,但我没有找到任何解释如何使用python-docx更新MS Word中的字段的主题。它还没有实现吗?
我所指的字段位于高级文档属性/自定义中。
Fields configured in Advanced Document Properties menu
发布于 2020-06-26 17:16:34
解决方案1
user:1902513或scanny还没有在python-docx的主存储库中实现custom_properties属性--而且可能不会在不久的将来实现,因为他说没有开发人员积极修改存储库。
我的建议是重新安装模块,但从user:652546或renejsum;here制作的不同存储库副本中重新安装。
用法示例与this script中相同。
发布于 2020-06-26 17:23:42
解决方案2
您可以通过浏览其关键字来更改各个自定义属性的文本。
示例:
from re import compile # regex module to emulate keyword search by pattern
keyword = re.compile(r'\s*Creator: (?P<creator_name>\w+)\s*')
word_replacement = 'Daniel Serrano'
for _p in doc.paragraphs: # doc = docx.Document(...)
found_word = keyword.match(_p.text)
if found_word:
for _r in _p.runs:
_r.text = _r.text.replace(
found_word.group('creator_name'),
word_replacement
)最好避免在_p.text本身上设置更改,尽管这是可行的,因为它可能会重新格式化运行(即。粗体、斜体、下划线删除)。
https://stackoverflow.com/questions/62449291
复制相似问题