簡體   English   中英

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

[英]How to update fields in MS Word with Python Docx

我正在開發一個 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是 select 是否添加圖或表標題編號。


我找到了更新字段的示例,但這會在打開文檔時打開以下 window:

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)

彈出窗口


有沒有辦法在沒有彈出 window 並且不向 Word 文檔中添加宏的情況下做到這一點? 這需要在 MacOS 和 Windows 上工作。

問題中描述的行為是設計使然。 更新字段是一個潛在的安全風險 - 有一些字段類型可以訪問外部內容。 因此,在 Word UI 之外生成的動態內容需要用戶確認才能更新。

我只知道三種防止顯示提示的方法

  1. 在文檔生成期間計算值並插入字段結果。 這些字段仍然可以以正常方式更新,但在第一次打開文檔時不需要更新。 (省略問題第二部分的代碼。)

  2. 使用 Word Automation Services(需要本地 SharePoint)打開文檔,這將更新字段(如問題的第二部分所示)。

  3. 包括在AutoOpen宏中執行字段更新的 VBA 項目。 當然,這意味着文檔類型必須啟用宏 (docm),並且允許在目標安裝上執行宏(當然,這也是一個安全風險)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM