【发布时间】:2015-10-07 12:39:14
【问题描述】:
我使用python包“python-docx”来修改MS word .docx文档的结构和内容。该软件包无法更新 TOC(目录)[Python: Create a "Table Of Contents" with python-docx/lxml。
是否有更新文档目录的解决方法?我曾考虑使用 python 包“pywin32”[https://pypi.python.org/pypi/pypiwin32] 中的“win32com.client”或为 MS Office 提供“cli 控制”功能的类似 pypi 包。
我尝试了以下方法:
我将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.Quit())。但是目录没有更新。
在宏执行之后,ms word 是否会执行我没有考虑过的其他操作?
【问题讨论】:
标签: python pywin32 win32com python-docx