使用Python

时间:2015-10-07 12:39:15

标签: python pywin32 win32com python-docx

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

是否有更新文档TOC的变通方法?我想过使用" win32com.client"来自python包" pywin32" [https://pypi.python.org/pypi/pypiwin32]或类似的pypi包提供" cli控制" MS Office的功能。

我尝试了以下内容:

我将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

如果我更改内容(添加/删除标题)并运行宏,则更新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字是否会执行其他操作?

3 个答案:

答案 0 :(得分:4)

这是一个更新单词2013 .docx文档的TOC的片段,其中仅包含一个内容表(例如,标题的TOC,没有数字的TOC等)。如果使用python update_toc.py命令promt(windows 10,命令promt而非“以管理员身份运行”)运行脚本 update_toc.py ,则系统安装python会打开文件 doc_with_toc .docx 在同一目录中,更新TOC(在我的情况下是标题)并将更改保存到同一文件中。该文档可能无法在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()

答案 1 :(得分:0)

要更新TOC,这对我有用:

word = win32com.client.DispatchEx("Word.Application")
Selection = word.Selection 
Selection.Fields.Update

答案 2 :(得分:0)

我使用docxtpl python软件包自动生成docx文件。 该文档包含许多自动生成的表。

我需要在模板生成后更新整个文档(以刷新生成的表号以及目录,图和表的表)。 我不太熟练使用VBA,也不知道用于此更新的功能。为了找到它们,我通过“记录宏”按钮创建了一个单词Macro。 我将自动生成的代码翻译为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()