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

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

准备工作

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

cs 复制代码
PM> Install-Package Spire.Doc

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

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

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

完整示例代码如下:

cs 复制代码
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 属性,可以为段落指定相应的大纲级别;随后,可以将这些级别应用到目录的生成规则中。具体步骤如下:

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

完整示例代码如下:

cs 复制代码
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 文档中,可以根据图片的题注生成相应的目录。通过设置目录字段,使其识别指定的图片题注样式,即可将带有题注的图片整理到目录中。具体步骤如下:

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

完整示例代码如下:

cs 复制代码
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 文档中,也可以根据表格题注生成相应的目录。通过设置目录字段,使其识别指定的表格题注样式,即可将文档中的表格整理到目录中。具体步骤如下:

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

完整示例代码如下:

cs 复制代码
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 文件。

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

相关推荐
czhc11400756632 小时前
同一个数,两把尺子:六组“看着一样、其实不一样“
c#
花北城3 小时前
【C#底层库】access_token授权鉴权验证
c#·鉴权·token·授权
SunnyDays10113 小时前
Java 拆分 Word 文档教程:按页、分页符和分节符拆分
java·word·分页·拆分
rick9773 小时前
C# 动态代理与 DispatchProxy:从原理到实战的完整指南
c#
tang_04273 小时前
【Hi.Ltd 专题】第8期:Managements 插件、单例与服务定位
经验分享·c#·hi.ltd系列
曹牧14 小时前
C#:24小时制时间
c#
唐青枫20 小时前
别急着拆服务:C#.NET 微服务架构从边界设计到实战
c#·.net
czhc11400756631 天前
从一份运行日志还原一次生产卡死:三个信号与一场“假卡死“
c#
Jazz_z1 天前
如何用 C# 读取 Word 中的表格数据
开发语言·c#