如何使用Python Docx更新MS Word中的字段
我正在开发一个Python程序,该程序需要在MS Word中将标题文本添加到图形和表格中(带有编号)。但是,添加字段后,在我更新字段之前,字段不会出现在Word文档中(在我更新字段之前,它只是文档中的一个空白,然后跳到例如“2”) 这是我添加字段的代码:如何使用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_
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之外生成的动态内容需要用户确认才能更新 我只知道三种防止显示提示的方法
AutoOpen
宏中执行字段更新。当然,这意味着文档类型必须启用宏(docm),并且允许在目标安装上执行宏(当然也存在安全风险)