首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >使用C#代码为新创建的 Word 文档创建目录

使用C#代码为新创建的 Word 文档创建目录

原创
作者头像
用户12401097
发布2026-09-18 15:35:55
发布2026-09-18 15:35:55
530
举报

在新创建的 Word 文档中添加目录,可以帮助读者快速了解文档结构,并更方便地定位和浏览所需内容。目录不仅能够提升文档的整体可读性,还可以在内容较多时提高信息查找效率。本文将介绍如何在 C# 项目中创建一个新的 Word 文档,并为其添加目录。

准备工作

首先,需要在 .NET 项目中添加相应的 Word 文档处理组件。可以从相关页面下载并引用 DLL 文件,也可以通过 NuGet 安装对应的程序包。

代码语言:C#
复制
PM> Install-Package Spire.Doc

C# 使用标题样式创建目录

在 Word 文档中,可以通过设置不同级别的标题样式来区分标题和小标题,并据此生成目录。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.AddSection() 方法添加一个节。
  3. 使用 Section.AddParagraph() 方法添加段落。
  4. 使用 Paragraph.AppendTOC(int lowerLevel, int upperLevel) 方法创建目录。
  5. 创建 CharacterFormat 对象并设置字体。
  6. 使用 Paragraph.ApplyStyle(BuiltinStyle.Heading1) 方法为段落应用标题样式。
  7. 使用 Paragraph.AppendText() 方法添加文本内容。
  8. 使用 TextRange.ApplyCharacterFormat() 方法设置文本的字符格式。
  9. 使用 Document.UpdateTableOfContents() 方法更新目录。
  10. 使用 Document.SaveToFile() 方法保存文档。

完整示例代码如下:

代码语言:C#
复制
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的文档对象
            Document doc = new Document();

            // 为文档添加一个节
            Section section = doc.AddSection();

            // 添加一个段落
            Paragraph TOCparagraph = section.AddParagraph();
            TOCparagraph.AppendTOC(1, 3);

            // 创建 CharacterFormat 对象并设置字体
            CharacterFormat characterFormat1 = new CharacterFormat(doc);
            characterFormat1.FontName = "Microsoft YaHei";

            // 创建另一个 CharacterFormat 对象
            CharacterFormat characterFormat2 = new CharacterFormat(doc);
            characterFormat2.FontName = "Microsoft YaHei";
            characterFormat2.FontSize = 12;

            // 添加一个应用“标题 1”样式的段落
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);

            // 添加文本并设置字符格式
            TextRange textRange1 = paragraph.AppendText("概述");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通正文内容
            paragraph = section.Body.AddParagraph();
            TextRange textRange2 = paragraph.AppendText("Spire.Doc for .NET 是一个面向开发人员的 Word .NET 类库,可用于在不同 .NET 平台上创建、读取、写入、转换、比较和打印 Word 文档。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加一个应用“标题 1”样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);
            textRange1 = paragraph.AppendText("主要功能");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加一个应用“标题 2”样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("无需 Microsoft Office 自动化");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通正文内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("该组件可以在不安装 Microsoft Office 的情况下处理 Word 文档。Microsoft Office 自动化在生成 Word 文档时可能存在稳定性、速度和扩展性方面的问题,因此可以根据实际需求选择合适的文档处理方式。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加一个应用“标题 3”样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading3);
            textRange1 = paragraph.AppendText("Word 版本");
            textRange1.ApplyCharacterFormat(characterFormat1);

            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加一个应用“标题 2”样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("高质量转换文档");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通正文内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("通过相关文档处理功能,用户可以将 Word Doc/Docx 文档保存到流中、作为 Web 响应返回,也可以在多种文档格式之间进行转换,例如 XML、Markdown、RTF、EMF、TXT、XPS、EPUB、HTML、SVG 和 ODT 等。此外,还可以将 Word Doc/Docx 转换为 PDF,以及将 HTML 转换为图像。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 添加一个应用“标题 2”样式的段落
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("其他技术特性");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // 添加普通正文内容
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("开发人员可以根据实际需求,在 ASP.NET、Web Services、WinForms、Xamarin 和 Mono Android 等 .NET 应用程序中处理 Word 文档。");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // 更新目录
            doc.UpdateTableOfContents();

            // 保存文档
            doc.SaveToFile("CreateTOCUsingHeadingStyles.docx", FileFormat.Docx2016);

            // 释放资源
            doc.Dispose();
        }
    }
}

C# 使用大纲级别样式创建目录

在 Word 文档中,也可以通过设置段落的大纲级别来生成目录。通过 ParagraphFormat.OutlineLevel 属性,可以为段落指定相应的大纲级别;随后,可以将这些级别应用到目录的生成规则中。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.AddSection() 方法添加一个节。
  3. 创建 ParagraphStyle 对象,并通过 ParagraphStyle.ParagraphFormat.OutlineLevel = OutlineLevel.Level1 设置大纲级别。
  4. 使用 Document.Styles.Add() 方法将创建的 ParagraphStyle 对象添加到文档中。
  5. 使用 Section.AddParagraph() 方法添加段落。
  6. 使用 Paragraph.AppendTOC(int lowerLevel, int upperLevel) 方法创建目录。
  7. 将目录默认使用标题样式的设置设为 False,即 TableOfContent.UseHeadingStyles = false。
  8. 使用 TableOfContent.SetTOCLevelStyle(int levelNumber, string styleName) 方法,将设置的大纲级别样式应用到目录生成规则中。
  9. 创建 CharacterFormat 对象并设置字体。
  10. 使用 Paragraph.ApplyStyle(ParagraphStyle.Name) 方法为段落应用相应样式。
  11. 使用 Paragraph.AppendText() 方法添加文本内容。
  12. 使用 TextRange.ApplyCharacterFormat() 方法设置文本的字符格式。
  13. 使用 Document.UpdateTableOfContents() 方法更新目录。
  14. 使用 Document.SaveToFile() 方法保存文档。

完整示例代码如下:

代码语言:C#
复制
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个文档对象
            Document doc = new Document();
            Section section = doc.AddSection();

            // 定义大纲级别 1
            ParagraphStyle titleStyle1 = new ParagraphStyle(doc);
            titleStyle1.Name = "T1S";
            titleStyle1.ParagraphFormat.OutlineLevel = OutlineLevel.Level1;
            titleStyle1.CharacterFormat.Bold = true;
            titleStyle1.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle1.CharacterFormat.FontSize = 18f;
            titleStyle1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle1);

            // 定义大纲级别 2
            ParagraphStyle titleStyle2 = new ParagraphStyle(doc);
            titleStyle2.Name = "T2S";
            titleStyle2.ParagraphFormat.OutlineLevel = OutlineLevel.Level2;
            titleStyle2.CharacterFormat.Bold = true;
            titleStyle2.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle2.CharacterFormat.FontSize = 16f;
            titleStyle2.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle2);

            // 定义大纲级别 3
            ParagraphStyle titleStyle3 = new ParagraphStyle(doc);
            titleStyle3.Name = "T3S";
            titleStyle3.ParagraphFormat.OutlineLevel = OutlineLevel.Level3;
            titleStyle3.CharacterFormat.Bold = true;
            titleStyle3.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle3.CharacterFormat.FontSize = 14f;
            titleStyle3.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle3);

            // 添加一个段落
            Paragraph TOCparagraph = section.AddParagraph();
            TableOfContent toc = TOCparagraph.AppendTOC(1, 3);
            toc.UseHeadingStyles = false;
            toc.UseHyperlinks = true;
            toc.UseTableEntryFields = false;
            toc.RightAlignPageNumbers = true;
            toc.SetTOCLevelStyle(1, titleStyle1.Name);
            toc.SetTOCLevelStyle(2, titleStyle2.Name);
            toc.SetTOCLevelStyle(3, titleStyle3.Name);

            // 定义字符格式
            CharacterFormat characterFormat = new CharacterFormat(doc);
            characterFormat.FontName = "Microsoft YaHei";
            characterFormat.FontSize = 12;

            // 添加一个段落并应用大纲级别 1 样式
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("概述");

            // 添加一个段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            TextRange textRange = paragraph.AppendText("该 Word .NET 类库可用于在不同 .NET 平台上创建、读取、写入、转换、比较和打印 Word 文档。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加一个段落并应用大纲级别 1 样式
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("主要功能");

            // 添加一个段落并应用大纲级别 2 样式
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("无需 Microsoft Office 自动化");

            // 添加一个段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("该组件可以在不安装 Microsoft Office 的情况下处理 Word 文档。对于 Word 文档的生成和处理,可以根据项目需求选择合适的技术方案。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加一个段落并应用大纲级别 3 样式
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle3.Name);
            paragraph.AppendText("Word 版本");

            // 添加一个段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加一个段落并应用大纲级别 2 样式
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("文档格式转换");

            // 添加一个段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("用户可以将 Word Doc/Docx 文档保存到流中、作为 Web 响应返回,并在 XML、Markdown、RTF、EMF、TXT、XPS、EPUB、HTML、SVG 和 ODT 等格式之间进行转换。此外,还可以将 Word Doc/Docx 转换为 PDF,以及将 HTML 转换为图像。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 添加一个段落并应用大纲级别 2 样式
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("其他技术特性");

            // 添加一个段落并设置文本内容
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("开发人员可以根据项目需求,在 ASP.NET、Web Services、WinForms、Xamarin 和 Mono Android 等 .NET 应用程序中创建和处理 Word 文档。");
            textRange.ApplyCharacterFormat(characterFormat);

            // 更新目录
            doc.UpdateTableOfContents();

            // 保存文档
            doc.SaveToFile("CreateTOCUsingOutlineStyles.docx", FileFormat.Docx2016);

            // 释放资源
            doc.Dispose();
        }
    }
}

C# 使用图片题注创建目录

在 Word 文档中,可以根据图片的题注生成相应的目录。通过设置目录字段,使其识别指定的图片题注样式,即可将带有题注的图片整理到目录中。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.AddSection() 方法添加一个节。
  3. 使用 TableOfContent tocForImage = new TableOfContent(Document, " \h \z \c \"Image\"") 创建目录对象,并指定目录的相关设置。
  4. 使用 Section.AddParagraph() 方法添加段落。
  5. 使用 Paragraph.Items.Add(tocForImage) 方法将目录对象添加到段落中。
  6. 使用 Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) 方法添加字段分隔符。
  7. 使用 Paragraph.AppendText("TOC") 方法添加文本内容 “TOC”。
  8. 使用 Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) 方法添加字段结束标记。
  9. 使用 Paragraph.AppendPicture() 方法添加图片。
  10. 使用 DocPicture.AddCaption() 方法为图片添加题注,并根据需要设置相关内容和格式。
  11. 使用 Document.UpdateTableOfContents(tocForImage) 方法更新目录,使其反映文档中的最新内容。
  12. 使用 Document.SaveToFile() 方法保存文档。

完整示例代码如下:

代码语言:C#
复制
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个文档对象
            Document doc = new Document();

            // 为文档添加一个节
            Section section = doc.AddSection();

            // 创建一个用于图片的目录对象
            TableOfContent tocForImage = new TableOfContent(doc, " \\h \\z \\c \"Picture\"");

            // 为节添加一个段落
            Paragraph tocParagraph = section.Body.AddParagraph();

            // 将目录对象添加到段落中
            tocParagraph.Items.Add(tocForImage);

            // 添加字段分隔符
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);

            // 添加文本内容
            tocParagraph.AppendText("TOC");

            // 添加字段结束标记
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // 为节添加一个空段落
            section.Body.AddParagraph();

            // 为节添加一个段落
            Paragraph paragraph = section.Body.AddParagraph();

            // 添加图片
            DocPicture docPicture = paragraph.AppendPicture("images/Doc-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;

            // 为图片添加题注段落
            Paragraph pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Doc for .NET 产品");
            pictureCaptionParagraph.Format.AfterSpacing = 20;

            // 继续向节中添加段落
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PDF-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.PDF for .NET 产品");
            pictureCaptionParagraph.Format.AfterSpacing = 20;

            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/XLS-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.XLS for .NET 产品");
            pictureCaptionParagraph.Format.AfterSpacing = 20;

            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PPT-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Presentation for .NET 产品");

            // 更新目录
            doc.UpdateTableOfContents(tocForImage);

            // 将文档保存到文件
            doc.SaveToFile("CreateTOCWithImageCaptions.docx", Spire.Doc.FileFormat.Docx2016);

            // 释放文档对象
            doc.Dispose();
        }
    }
}

C# 使用表格题注创建目录

在 Word 文档中,也可以根据表格题注生成相应的目录。通过设置目录字段,使其识别指定的表格题注样式,即可将文档中的表格整理到目录中。具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.AddSection() 方法添加一个节。
  3. 使用 TableOfContent tocForTable = new TableOfContent(Document, " \h \z \c \"Table\"") 创建目录对象,并设置目录的相关规则。
  4. 使用 Section.AddParagraph() 方法添加段落。
  5. 使用 Paragraph.Items.Add(tocForTable) 方法将目录对象添加到段落中。
  6. 使用 Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) 方法添加字段分隔符。
  7. 使用 Paragraph.AppendText("TOC") 方法添加文本内容 “TOC”。
  8. 使用 Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) 方法添加字段结束标记。
  9. 使用 Section.AddTable() 方法添加表格,并通过 Table.ResetCells(int rowsNum, int columnsNum) 方法设置表格的行数和列数。
  10. 使用 Table.AddCaption() 方法为表格添加题注,并根据需要设置相关内容和格式。
  11. 使用 Document.UpdateTableOfContents(tocForTable) 方法更新目录,使其反映文档中的最新内容。
  12. 使用 Document.SaveToFile() 方法保存文档。

完整示例代码如下:

代码语言:C#
复制
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新文档
            Document doc = new Document();

            // 为文档添加一个节
            Section section = doc.AddSection();

            // 创建一个 TableOfContent 对象
            TableOfContent tocForTable = new TableOfContent(doc, " \\h \\z \\c \"Table\"");

            // 在节中添加一个段落,用于放置 TableOfContent 对象
            Paragraph tocParagraph = section.Body.AddParagraph();
            tocParagraph.Items.Add(tocForTable);
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);
            tocParagraph.AppendText("TOC");
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // 在节中添加两个空段落
            section.Body.AddParagraph();
            section.Body.AddParagraph();

            // 在节中添加一个表格
            Table table = section.Body.AddTable(true);
            table.ResetCells(1, 3);

            // 为表格添加题注段落
            Paragraph tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  一行三列");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // 在节中添加一个新表格
            table = section.Body.AddTable(true);
            table.ResetCells(3, 3);

            // 为第二个表格添加题注段落
            tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  三行三列");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // 在节中添加另一个新表格
            table = section.Body.AddTable(true);
            table.ResetCells(5, 3);

            // 为第三个表格添加题注段落
            tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  五行三列");

            // 更新目录
            doc.UpdateTableOfContents(tocForTable);

            // 将文档保存到指定文件
            doc.SaveToFile("CreateTOCUsingTableCaptions.docx", Spire.Doc.FileFormat.Docx2016);

            // 释放资源
            doc.Dispose();
        }
    }
}

总结

在 Word 文档中创建表格目录,可以帮助读者快速了解文档中的表格信息,并根据题注定位相应内容。通过为表格添加统一的题注格式,再设置目录字段,即可将这些表格题注集中显示在目录中。

本文介绍了如何在 C# 项目中创建 Word 文档、添加表格及表格题注,并根据题注生成表格目录。完成文档内容设置后,通过更新目录可以使其与文档中的表格内容保持同步,最后将生成的文档保存为 DOCX 文件。

这种方式适用于包含多个表格的报告、说明文档等场景,也可以根据实际需求调整表格数量、题注内容以及目录的显示方式。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 准备工作
  • C# 使用标题样式创建目录
  • C# 使用大纲级别样式创建目录
  • C# 使用图片题注创建目录
  • C# 使用表格题注创建目录
  • 总结
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档