本篇文章将介绍通过Spire.Doc for .NET来创建Word目录的方法。这里创建Word目录的方法中需手动设置段落的大纲级别来创建目录;如文档中已设置大纲级别,可通过域代码来创建目录(可参考这篇教程)。
C#
//加载源文档
Document doc = new Document();
doc.LoadFromFile("test.docx");
//插入一个段落
Paragraph paraInserted = new Paragraph(doc);
TextRange textRange = paraInserted.AppendText("目 录");
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.TextColor = Color.CadetBlue;
doc.Sections[0].Paragraphs.Insert(0, paraInserted);
paraInserted.Format.HorizontalAlignment = HorizontalAlignment.Center;
//添加目录
doc.Sections[0].Paragraphs[0].AppendTOC(1, 3);
doc.Sections[0].Paragraphs[2].ApplyStyle(BuiltinStyle.Heading1);
doc.Sections[0].Paragraphs[5].ApplyStyle(BuiltinStyle.Heading2);
doc.Sections[0].Paragraphs[7].ApplyStyle(BuiltinStyle.Heading2);
doc.Sections[0].Paragraphs[9].ApplyStyle(BuiltinStyle.Heading2);
doc.Sections[0].Paragraphs[12].ApplyStyle(BuiltinStyle.Heading1);
doc.Sections[0].Paragraphs[14].ApplyStyle(BuiltinStyle.Heading1);
doc.Sections[0].Paragraphs[16].ApplyStyle(BuiltinStyle.Heading1);
//更新目录
doc.UpdateTableOfContents();
//保存文档
doc.SaveToFile("result.docx", FileFormat.Docx2010);
VB.NET
Dim doc As Document = New Document
doc.LoadFromFile("test.docx")
Dim paraInserted As Paragraph = New Paragraph(doc)
Dim textRange As TextRange = paraInserted.AppendText("目 录")
textRange.CharacterFormat.Bold = true
textRange.CharacterFormat.TextColor = Color.CadetBlue
doc.Sections(0).Paragraphs.Insert(0, paraInserted)
paraInserted.Format.HorizontalAlignment = HorizontalAlignment.Center
doc.Sections(0).Paragraphs(0).AppendTOC(1, 3)
doc.Sections(0).Paragraphs(2).ApplyStyle(BuiltinStyle.Heading1)
doc.Sections(0).Paragraphs(5).ApplyStyle(BuiltinStyle.Heading2)
doc.Sections(0).Paragraphs(7).ApplyStyle(BuiltinStyle.Heading2)
doc.Sections(0).Paragraphs(9).ApplyStyle(BuiltinStyle.Heading2)
doc.Sections(0).Paragraphs(12).ApplyStyle(BuiltinStyle.Heading1)
doc.Sections(0).Paragraphs(14).ApplyStyle(BuiltinStyle.Heading1)
doc.Sections(0).Paragraphs(16).ApplyStyle(BuiltinStyle.Heading1)
doc.UpdateTableOfContents
doc.SaveToFile("result.docx", FileFormat.Docx2010)
目录生成效果: