相关疑难解决方法(0)

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

我使用python包“python-docx”来修改MS word .docx文档的结构和内容。该包无法更新 TOC(目录)[ Python:使用 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
Run Code Online (Sandbox Code Playgroud)

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

我实现了以下 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...')
Run Code Online (Sandbox Code Playgroud)

update_toc(docx_file) 在更高级别的脚本中调用(它操作文档的 TOC …

python pywin32 win32com python-docx

7
推荐指数
1
解决办法
9793
查看次数

Python:使用python-docx/lxml创建"目录"

我试图在python-docx(https://github.com/mikemaccana/python-docx)的帮助下自动创建.docx文件(WordML ).我当前的脚本使用以下循环手动创建ToC:

for chapter in myChapters:
    body.append(paragraph(chapter.text, style='ListNumber'))
Run Code Online (Sandbox Code Playgroud)

有没有人知道使用"内置单词"ToC功能的方法,它会自动添加索引并创建各个章节的段落链接?

非常感谢!

python docx wordml python-docx

5
推荐指数
4
解决办法
8028
查看次数

标签 统计

python ×2

python-docx ×2

docx ×1

pywin32 ×1

win32com ×1

wordml ×1