gpt4 book ai didi

python - 使用 Python 更新 MS Word .docx 文档的目录(目录)

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:11 30 4
gpt4 key购买 nike

我使用 python 包“python-docx”来修改 MS word .docx 文档的结构和内容。该软件包无法更新目录(目录)[ Python: Create a "Table Of Contents" with python-docx/lxml .

是否有更新文档目录的解决方法?我考虑过使用 python 包“pywin32”中的“win32com.client”[https://pypi.python.org/pypi/pypiwin32]或类似的 pypi 包,为 MS Office 提供“cli 控制”功能。

我尝试了以下方法:

我将 document.docx 更改为 document.docm 并实现了以下宏 [ http://word.tips.net/T000301_Updating_an_Entire_TOC_from_a_Macro.html] :

Sub update_TOC()

If ActiveDocument.TablesOfContents.Count = 1 Then _
ActiveDocument.TablesOfContents(1).Update

End Sub

如果我更改内容(添加/删除标题)并运行宏,目录就会更新。我保存文档,我很高兴。

我实现了以下应该等同于宏的 python 代码:

import win32com.client

def update_toc(docx_file):
word = win32com.client.DispatchEx("Word.Application")
doc = word.Documents.Open(docx_file)
toc_count = doc.TablesOfContents.Count
if toc_count == 1:
toc = doc.TablesOfContents(1)
toc.Update
print('TOC should have been updated.')
else:
print('TOC has not been updated for sure...')

update_toc(docx_file) 在更高级别的脚本(操作文档的 TOC 相关内容)中调用。调用此函数后,文档将被保存 (doc.Save())、关闭 (doc.Close()) 并关闭 word 实例 (word.Quit())。但是 TOC 没有更新。

ms word 执行宏后是否执行我没有考虑的其他操作?

最佳答案

这是更新 word 2013 .docx 文档目录的片段,该文档仅包含一个目录(例如,只有标题目录,没有图表目录等)。如果脚本 update_toc.py 使用 python update_toc.py 从命令提示符(Windows 10,命令提示符不是“以管理员身份运行”)运行,则 python 的系统安装将打开同一目录中的文件 doc_with_toc.docx,更新目录(在我的例子中是标题)并将更改保存到同一文件中。该文档可能无法在 Word 2013 的另一个实例中打开,并且可能没有写保护。请注意,此脚本执行 not the same as selecting the whole document content and pressing the F9 key .

update_toc.py 的内容:

import win32com.client
import inspect, os

def update_toc(docx_file):
word = win32com.client.DispatchEx("Word.Application")
doc = word.Documents.Open(docx_file)
doc.TablesOfContents(1).Update()
doc.Close(SaveChanges=True)
word.Quit()

def main():
script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
file_name = 'doc_with_toc.docx'
file_path = os.path.join(script_dir, file_name)
update_toc(file_path)

if __name__ == "__main__":
main()

关于python - 使用 Python 更新 MS Word .docx 文档的目录(目录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992457/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com