我使用python包“python”修改MS .docx文档的结构和内容。该软件包缺乏更新TOC (内容表) [Python:用python/lxml创建一个“目录” ]的可能性。
是否有其他方法来更新文档的TOC?我考虑使用python包"pywin32“[https://pypi.python.org/pypi/pypiwin32]中的”pywin32“,或者为MS提供"cli控制”功能的类似pypi包。
我尝试了以下几点:
我将document.docx更改为document.docm,并实现了以下宏Macro.html]
Sub update_TOC()
If ActiveDocument.TablesOfContents.Count = 1 Then _
ActiveDocument.TablesOfContents(1).Update
End Sub如果我更改内容(添加/删除标题)并运行宏,TOC将被更新。我保存了文件,我很高兴。
我实现了以下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())。然而,TOC没有更新。
ms是否在宏执行后执行我没有考虑过的附加操作?
发布于 2016-01-15 19:58:32
下面是一个更新word 2013 .docx文档TOC的片段,该文档只包含一个内容表(例如,仅包含标题的TOC,没有TOC的数字等等)。如果脚本update_toc.py是从命令promt (windows 10,命令promt而不是"running“)运行,那么python的系统安装将在同一个目录中打开文件,更新TOC (在我的示例中是标题),并将更改保存到同一个文件中。该文档可能不会在Word 2013的另一个实例中打开,也可能不会受到写入保护。请注意,此脚本执行与选择整个文档内容和按F9键不同。
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()发布于 2019-07-02 15:45:58
我使用docxtpl python包自动生成docx文件。此文档包含许多自动生成的表。
我需要在模板生成之后更新整个文档(刷新生成的表号以及内容表、图形表和表表)。我不太熟悉VBA,也不知道这些更新的功能。为了找到它们,我通过“记录宏”按钮创建了一个单词宏。我将自动生成的代码翻译到python,结果如下。我认为可以通过python执行任何单词操作。
def DocxUpdate(docx_file):
word = win32com.client.DispatchEx("Word.Application")
doc = word.Documents.Open(docx_file)
# update all figure / table numbers
word.ActiveDocument.Fields.Update()
# update Table of content / figure / table
word.ActiveDocument.TablesOfContents(1).Update()
word.ActiveDocument.TablesOfFigures(1).Update()
word.ActiveDocument.TablesOfFigures(2).Update()
doc.Close(SaveChanges=True)
word.Quit()发布于 2015-11-24 08:54:56
为了更新TOC,这对我起了作用:
word = win32com.client.DispatchEx("Word.Application")
Selection = word.Selection
Selection.Fields.Updatehttps://stackoverflow.com/questions/32992457
复制相似问题