Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python Docx更新MS Word中的字段_Python_Xml_Ms Word_Docx_Python Docx - Fatal编程技术网

如何使用Python Docx更新MS Word中的字段

如何使用Python Docx更新MS Word中的字段,python,xml,ms-word,docx,python-docx,Python,Xml,Ms Word,Docx,Python Docx,我正在开发一个Python程序,该程序需要在MS Word中将标题文本添加到图形和表格中(带有编号)。但是,添加字段后,在我更新字段之前,字段不会出现在Word文档中(在我更新字段之前,它只是文档中的一个空白,然后跳到例如“2”) 这是我添加字段的代码: def add_caption_number(self, field_code): """ Add a caption number for the field :argument field_

我正在开发一个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_paration
是已添加的最后一段,
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上运行。

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

我只知道三种防止显示提示的方法

  • 在文档生成过程中计算值并插入字段结果。这些字段仍然可以以正常方式更新,但在第一次打开文档时不需要更新。(删去问题第二部分的代码。)

  • 使用Word Automation Services(需要内部SharePoint)打开文档,文档将更新字段(如问题的第二部分)

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