700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > pythondocx更新目录_使用Python更新MS Word .docx文档的目录(目录)

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

时间:2019-06-15 09:41:31

相关推荐

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

是否有解决方法来更新文档的目录?我考虑过使用python软件包“ pywin32” [/pypi/pypiwin32]]或可比的pypi软件包中的“ win32com.client”,该软件包为MS Office提供“ cli control”功能.

我尝试了以下方法:

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()).但是,TOC尚未更新.

ms word是否在宏执行后执行了我未考虑的其他操作?

解决方法:

这是一个代码片段,用于更新单词 .docx文档的目录,仅包含一个目录(例如仅标题的TOC,不包含图形的TOC等).如果使用python update_toc.py从命令promt(Windows 10,命令promt不“以管理员身份运行”)运行脚本update_toc.py,则python的系统安装程序会在同一目录中打开文件doc_with_toc.docx,更新目录(以我的标题为准),并将更改保存到同一文件中.该文档可能不会在Word 的另一个实例中打开,并且可能没有写保护.请注意,此脚本的功能为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-docx,pywin32,win32com,python

来源: https://codeday.me/bug/1027/1947407.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。