本篇文章将介绍通过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)
目录生成效果: