Click here to Skip to main content
15,885,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I need to add TOC in a word document programmatically with configurable title.
Eg:

List of Images
1.0 Introduction (Heading 1).............2
1.1 Next (Header 2)..............4
1.1.1 Next (Header 2)......5
1.1.2 Final (Header 2).....6
2.0 Introduction (Heading 1).............7
2.1 Next (Header 2)..............8
2.1.1 Next (Header 2)......8
2.1.2 Final (Header 2).....9

Thanks & Regards,
Ratheesh
Posted
Updated 20-Apr-15 16:21pm
v2

1 solution

Hi, try this:
C#
var application = new Application();
var document = application.Documents.Open(FileName: @"C:\Sample In.docx");

var tocRange = document.Range(0, 0);
var toc = document.TablesOfContents.Add(
    Range: tocRange,
    UseHeadingStyles: true);
toc.Update();

var tocTitleRange = document.Range(0, 0);
tocTitleRange.Text = "List of Images";
tocTitleRange.InsertParagraphAfter();
tocTitleRange.set_Style("Title");

document.SaveAs2(@"C:\Sample Out.docx");
document.Close();
application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
 
Share this answer
 
Comments
RS.Ratheesh 21-Apr-15 22:58pm    
Thanks Mario, Its working

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900