使用 C# 在 Word 中插入目录

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

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

  1. 设置环境使用Aspose.Words for .NET插入TOC
  2. 将Word文件加载到Document对象中并初始化DocumentBuilder对象
  3. 添加具有所需样式的目录标题
  4. 插入目录并插入分页符
  5. 填充空目录
  6. 保存包含 TOC 的输出 Word 文件

您可以在以下步骤的帮助下使用 C# *在 Word 中插入内容页面。通过加载 Word 文件并配置支持添加目录的 DocumentBuilder 类对象来启动该过程。使用 InsertTableOfContents() 方法添加标题和目录,并通过调用 UpdateFields() 方法填充空目录。

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

using System;
using Aspose.Words;
class Program
{
static void Main(string[] args) // Insert table of contents in Word using C#
{
new License().SetLicense("License.lic");
// Load the document
Document doc = new Document("example03.docx");
// Instantiate the DocumentBuilder object
DocumentBuilder builder = new DocumentBuilder(doc);
// Create ParagraphFormat object
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
// Store the existing style name
string defaultStyle = paragraphFormat.StyleName;
// Set style name and text alignment for the table of contents
paragraphFormat.StyleName = "Title";
paragraphFormat.Alignment = ParagraphAlignment.Center;
// Add title of TOC
builder.Writeln("Table of contents");
// Restore the text style
paragraphFormat.StyleName = defaultStyle;
// Insert a table of contents
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Insert page break for TOC
builder.InsertBreak(BreakType.PageBreak);
// Populate the empty table of contents
doc.UpdateFields();
// Save document with TOC
doc.Save("output.docx");
Console.WriteLine("Done");
}
}

使用此代码使用 C# 在 Word 中制作内容页。 InsertTableOfContents() 需要开关来控制目录的行为,例如 1-3 用于寻址标题 1、2 和 3,\h”用于使用超链接,\u”用于设置大纲级别。默认目录为空,并使用 UpdateFields() 方法填充。

本文教会了我们如何使用 C# 在 Word 中添加目录。要插入页眉和页脚,请参阅有关 如何使用 C# 在 DOCX 中插入页眉和页脚 的文章。

 简体中文