如何使用Python Docx更新MS Word中的字段 [英] How to update fields in MS Word with Python Docx

查看:35
本文介绍了如何使用Python Docx更新MS Word中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Python程序,需要在MS Word中添加标题文本到图形和表格(带编号)。然而,添加字段后,该字段不会出现在我的Word文档中,直到我更新了该字段(它在我的文档中只是一个空白,直到我更新了该字段,然后它会跳到例如‘2’)。

这是我添加该字段的代码:

def add_caption_number(self, field_code):
    """ Add a caption number for the field

        :argument
            field_code: [string] the type of field e.g. 'Figure', 'Table'...
    """
    # Set the pointer to the last paragraph (e.g. the 'Figure ' caption text)
    run = self.last_paragraph.add_run()
    r = run._r

    # Add a Figure Number field xml element
    fldChar = OxmlElement("w:fldChar")
    fldChar.set(qn("w:fldCharType"), "begin")
    r.append(fldChar)

    instrText = OxmlElement("w:instrText")
    instrText.text = " SEQ %s * ARABIC" % field_code
    r.append(instrText)

    fldChar = OxmlElement("w:fldChar")
    fldChar.set(qn("w:fldCharType"), "end")
    r.append(fldChar)

self.last_paragraph是已添加的最后一段,field_code是选择添加插图还是表格标题编号。


我找到了一个更新字段的示例,但这会在打开文档时打开以下窗口:

def update_fields(save_path):
    """ Automatically updates the fields when opening the word document """
    namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
    doc = DocxTemplate(save_path)

    element_updatefields = lxml.etree.SubElement(
        doc.settings.element, f"{namespace}updateFields"
    )
    element_updatefields.set(f"{namespace}val", "true")

    doc.save(save_path)


有没有一种方法可以在不使用弹出窗口和不向Word文档中添加宏的情况下完成此操作?这需要在MacOS和Windows btw上运行。

推荐答案

问题中描述的行为是故意设计的。更新字段是潜在的安全风险-某些字段类型可以访问外部内容。因此,在Word UI之外生成的动态内容需要用户确认才能更新。

我知道只有三种方法可以防止显示提示

  1. 在单据生成过程中计算值并插入字段结果。这些字段仍然是可更新的,但在第一次打开文档时不需要更新。(省略问题第二部分中的代码。)

  2. 使用Word Automation Services(需要预置的SharePoint)打开文档,这将更新域(如问题的第二部分所示)。

  3. AutoOpen宏中包含执行字段更新的VBA项目。当然,这意味着文档类型必须启用宏(DOCM),并且允许宏在目标安装上执行(当然,这也存在安全风险)。

这篇关于如何使用Python Docx更新MS Word中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆