使用 Python 在 Word 中插入目录

按照这篇简短文章中的步骤,使用 Python 在 Word 中插入目录。它通过提供必要的资源、编写应用程序的编程步骤列表以及展示如何使用 Python 在 Word 中添加内容页面的示例代码来帮助配置环境。您将学习通过解析现有 Word 文档的内容来将目录插入到现有文档中。

使用 Python 在 Word 中创建目录的步骤

  1. 通过安装 Aspose.Words for Python 通过 .NET 设置环境以转换文本以插入 TOC
  2. 将Word文件访问到Document类对象中并初始化DocumentBuilder对象
  3. 使用所需的样式插入目录标题
  4. 添加目录并插入分页符
  5. 填充默认的空目录
  6. 保存其中包含目录的 Word 文件

您可以通过以下非常简单的步骤使用 Python 在 Word 中插入内容页面,该过程将通过使用 Document 类加载 Word 文件来启动,并配置支持添加目录的 DocumentBuilder 类对象。使用 insert_table_of_contents() 方法插入标题和目录,并通过调用 update_fields() 方法填充默认的空目录。

使用 Python 在 Word 中生成目录的代码

import aspose.words as aw
# Path to the files
filePath = "Y://KnowledgeBase//TestData//"
# Load the API license in your application to manage TOC in DOCX
wordLic = aw.License()
wordLic.set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Instantiate the Document class object to load the source word
srcDoc = aw.Document(filePath + "Test1.docx")
# Instantiate the DocumentBuilder object
builder = aw.DocumentBuilder(srcDoc)
# Create ParagraphFormat object
paragraphFormat = builder.paragraph_format
# Store the existing style name
defaultStyle = paragraphFormat.style_name
# Set the style name and text alignment for the TOC
paragraphFormat.style_name = "Title"
paragraphFormat.alignment = aw.ParagraphAlignment.CENTER
# Add title of TOC
builder.writeln("Table of contents")
# Restore the text style
paragraphFormat.style_name = defaultStyle
# Insert a table of contents
builder.insert_table_of_contents("\\o \"1-3\" \\h \\z \\u")
# Insert the page break for TOC
builder.insert_break(aw.BreakType.PAGE_BREAK)
# Populate the table of contents.
# Save document with TOC
srcDocument.save("output.docx")
print ("Operation completed successfully")

使用此示例代码使用 Python 在 Word 中制作内容页面。 insert_table_of_contents() 方法需要开关来控制目录的行为,假设 1-3 用于寻址标题 1、2 和 3,\h”用于使用超链接,\u”用于使用用于设置轮廓级别。默认目录 (TOC) 为空,并使用 update_fields() 方法填充。

本主题启发了我们如何使用 Python 在 Word 中添加目录。要了解如何旋转 Word 文件中的文本,请参阅有关 使用 Python 在 Word 中旋转文本 的文章。

 简体中文