Create a new windows application project and add a button to it.
On click of that button, we will open a document and first add a heading 1 programmatically and then insert a table of content programmatically and update it
Than we will add reference to (Word 10.0 or 11.0 object library) within COM tab of Add reference dialog box.
After adding reference, we’ll add this directive using Microsoft.Office.Interop.Word than we’ll put the following code in the button click event handler
// For optional parameters create a missing object
object missing = System.Reflection.Missing.Value;
// Create an object for filename which is the file to be opened
object fileName = @”C:\MySecond.doc”;
// Create an object of application class
ApplicationClass WordApp = new ApplicationClass();
// open the document specified in the fileName variable
Document adoc = WordApp.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
Range myRange = adoc.Range(ref missing, ref missing);
myRange.InsertAfter(“Hello Mickey Mouse GG “);
object oStyleName = “Heading 1″;
myRange.set_Style(ref oStyleName);
object start=WordApp.ActiveDocument.Content.End – 1;
Range rangeForTOC = adoc.Range(ref start, ref missing);
TableOfContents toc=adoc.TablesOfContents.Add(rangeForTOC, ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
toc.Update();
Range rngTOC = toc.Range;
rngTOC.Font.Size = 10;
rngTOC.Font.Name = “Georgia“;
WordApp.Visible = true;
Bye…
RSS - Posts

awesome..
By: NVP on November 11, 2008
at 6:46 am
Hi, i have see this post where you Create and Update table of contents in word document using C# (Version 2000). I wonder if this can be done for word document(Version 2007)? If that is possible can you post saome sample for helping me. Thanks.
By: Joaquim Oliveira on February 8, 2009
at 4:12 pm
The TOC is crreating in document but not working
By: Bharat Sukhwal on February 19, 2009
at 6:49 am
Hi i couldnt open the word document itself
I m getting an exception ..i have pasted below
Unable to cast COM object of type ‘Word.ApplicationClass’ to interface type ‘Word._Application’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{00020970-0000-0000-C000-000000000046}’ failed due to the following error: No such interface supported (Exception from HRESULT: 0×80004002 (E_NOINTERFACE)).
Thank you
Mano
By: Anonymous on April 27, 2009
at 6:48 am