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


