none
Hww to add TOC(table of content) in word document using microsoft word interop in c#? RRS feed

  • Question

  • using System;
    using System.Windows.Forms;
    using System.Diagnostics;
    using Word = Microsoft.Office.Interop.Word;
    using System.Drawing;
    using System.Reflection;
    using Excel = Microsoft.Office.Interop.Excel;
    using Microsoft.Office.Interop.Word;


    namespace Chart
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                
                CreateDocument();
               
            }

     #region CreateDocument
            //Create document method
            private void CreateDocument()
            {
                try
                {

                    object oMissing = System.Reflection.Missing.Value;
                    object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

                    //Create an instance for word app
                    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                    //Set animation status for word application
                    //winword.ShowAnimation = false;

                    //Set status for word application is to be visible or not.It will simultaneously create the content of the document.
                    winword.Visible = false;

                    //Create a missing variable for missing value
                    object missing = System.Reflection.Missing.Value;

                    //Create a new document
                    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                   

                    #region Header Footer
                    //Add header into the document
                    foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                    {
                        //Get the header range and add the header details.
                        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                        headerRange.Fields.Add(headerRange, ref missing);
                        headerRange.InlineShapes.AddPicture(@"C:\Chart\Logo.png");
                        //headerRange.Text = string.Empty;
                    }     

                    //Add the footers into the document
                    foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                    {
                        //Get the footer range and add the footer details.
                        Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                        footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                        footerRange.Font.Size = 10;
                        footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                        footerRange.Text = "Copyright © 2012 All rights reserved.";
                    }

                    #endregion HeaderFooter

                    #region Document Name Section
                    //Create a paragraph and write the contents.
                    Microsoft.Office.Interop.Word.Paragraph titlePara = document.Content.Paragraphs.Add();                
                    titlePara.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                    titlePara.Range.InsertParagraphAfter();
                    titlePara.Range.Font.Name = "Calibri";
                    titlePara.Range.Font.Size = 26;
                    titlePara.Range.Text = Environment.NewLine
                        + "          Test Report" + Environment.NewLine
                        + "                                     For" + Environment.NewLine
                        + "                                 Test" + Environment.NewLine
                        + "                                     by" + Environment.NewLine
                        + "                             Test" + Environment.NewLine
                        + Environment.NewLine;
                    titlePara.Format.SpaceAfter = 24;
                    titlePara.Range.InsertParagraphAfter();

                    #endregion Document Name Section

                    #region Page break

                    Object nullobj = System.Reflection.Missing.Value;
                    Object objBreak = Word.WdBreakType.wdPageBreak;
                    Object objUnit = Word.WdUnits.wdStory;

                    winword.Selection.EndKey(ref objUnit, ref nullobj);
                    winword.Selection.InsertBreak(ref objBreak);

                    #endregion Page break

                    #region Table Section
                    //Create Header and Data
                    String[] Header = { "Test", "Test", "Test", "Test", "Test", "Test", "Test" };
                    String[][] data = {
                                              new String[]{ "Test","Test","Test","Test","Test","Test","Test"},
                                              new String[]{ "Test","Test","Test","Test","Test","Test","Test"},, 
                                              new String[]{ "Test","Test","Test","Test","Test","Test","Test"},,
                                              new String[]{ "Test","Test","Test","Test","Test","Test","Test"},,
                                          };
                     


                    Word.Table table;
                    Word.Range wrdRng = document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    table = document.Tables.Add(wrdRng, 5,7, ref oMissing, ref oMissing);
                    table.Range.ParagraphFormat.SpaceAfter = 6;
                    table.Range.Borders.Enable = 1;
                    table.Range.Cells.Borders.Enable = 1;

                    for (int i = 0; i < 1; i++)
                    {
                        for (int j = 0; j < Header.Length; j++)
                        {
                            table.Cell(i + 1, j + 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray15;
                            table.Cell(i + 1, j + 1).Range.Font.Size = 12;
                            table.Cell(i + 1, j + 1).Range.Text = Header.GetValue(j).ToString();
                        }
                    }

                    //For data
                    for (int i = 0; i < data.Length; i++)
                    {                    
                        for (int j = 0; j < data[i].Length; j++)
                        {
                            table.Cell(i + 1, j + 1).Range.Font.Size = 12;
                            if (j == 1 && data[i].GetValue(j).ToString() == "Critical")
                            {
                                table.Cell(i + 2, j + 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorDarkRed;
                                table.Cell(i + 2, j + 1).Range.Text = data[i].GetValue(j).ToString();
                            }
                            if (j == 1 && data[i].GetValue(j).ToString() == "High")
                            {
                                table.Cell(i + 2, j + 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorRed;
                                table.Cell(i + 2, j + 1).Range.Text = data[i].GetValue(j).ToString();
                            }
                            if (j == 1 && data[i].GetValue(j).ToString() == "Medium")
                            {
                                table.Cell(i + 2, j + 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGold;
                                table.Cell(i + 2, j + 1).Range.Text = data[i].GetValue(j).ToString();
                            }
                            if (j == 1 && data[i].GetValue(j).ToString() == "Low")
                            {
                                table.Cell(i + 2, j + 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorYellow;
                                table.Cell(i + 2, j + 1).Range.Text = data[i].GetValue(j).ToString();
                            }

                            table.Cell(i + 2, j + 1).Range.Text = data[i].GetValue(j).ToString();
                        }
                    }

                    #endregion Table Section

                    winword.Selection.EndKey(ref objUnit, ref nullobj);
                    winword.Selection.InsertBreak(ref objBreak);

                    #region Image Section
                    Word.Paragraph imgPara = document.Content.Paragraphs.Add();
                    imgPara.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    imgPara.Range.InlineShapes.AddPicture(@"C:\Chart\wallpaper.PNG");
                    #endregion Image Section              

                    //Add TOC

                    Range myRange = document.Range(ref missing, ref missing);
                    object oStyleName = "Heading 1";
                    object oTrueValue = true;
                    myRange.set_Style(ref oStyleName);
                    object start = winword.ActiveDocument.Content.End - 1;
                    Range rangeForTOC = document.Range(ref start, ref missing);
                    TableOfContents toc = document.TablesOfContents.Add(rangeForTOC, ref oTrueValue, UpperHeadingLevel: "1", LowerHeadingLevel: "3", UseFields: true, TableID: "TableOfContents", RightAlignPageNumbers: true, IncludePageNumbers: true, AddedStyles: true, UseHyperlinks: true, HidePageNumbersInWeb: true, UseOutlineLevels: true);

                   
                    
                    //Add TOC


                    winword.Selection.EndKey(ref objUnit, ref nullobj);
                    winword.Selection.InsertBreak(ref objBreak);

                    #region Complete Paragraph Section               
                    Word.Paragraph para = document.Paragraphs.Add(ref missing);
                   
                    para.Range.Text = "How To Read This Report";
                    para.Range.Bold = 1;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdBlue;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";                
                    para.Range.InsertParagraphAfter();

                    para.Range.Bold = 0;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdAuto;
                    para.Range.Font.Size = 12;
                    para.Range.Text = "This report has been split into the following sections:";
                    para.Range.InsertParagraphAfter();

                    para.Range.Text = "Executive Summary";
                    para.Range.Bold = 1;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdBlack;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";                
                    para.Range.InsertParagraphAfter();

                    para.Range.Text = "This section is prepared for the management and above, which contains graphical representation of the defects found, based on their type. The management can also have a glimpse of the instances of defects detected during the testing, their impact and likelihood of occurrence from ‘Summary of Findings’ section.";
                    para.Range.Bold = 0;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdAuto;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";
                    para.Format.SpaceAfter = 4;
                    para.Range.InsertParagraphAfter();

                    para.Range.Text = "Objective of testdocumnry";
                    para.Range.Bold = 1;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdBlack;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";
                    para.Range.InsertParagraphAfter();
                    para.Range.Text = "This section explains the purpose of testing document.";
                    para.Range.Bold = 0;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdAuto;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";
                    para.Format.SpaceAfter = 4;
                    para.Range.InsertParagraphAfter();

                    para.Range.Text = "Scope of Assessment";
                    para.Range.Bold = 1;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdBlack;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";
                    para.Range.InsertParagraphAfter();
                    para.Range.Text = "Scope of testing specifies which type of testing was done and which part of the testing.";
                    para.Range.Bold = 0;
                    para.Range.Font.ColorIndex = Word.WdColorIndex.wdAuto;
                    para.Range.Font.Size = 12;
                    para.Range.Font.Name = "Calibri";
                    para.Format.SpaceAfter = 4;
                    para.Range.InsertParagraphAfter();               

                  
                    #endregion Complete Paragraph Section
                    
                    //Save the document
                    object filename = @"C:\Chart\TestReport.docx";
                    document.SaveAs(ref filename);
                    //Below line is used to close the document if it is open.
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    
                }           

                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            #endregion CreateDocument
    }
    Wednesday, June 22, 2016 10:33 AM

All replies

  • One would have to wonder why you're creating all this from scratch instead of using a template with all the required standard content in-situ. Your current approach leaves your output at the mercy of whatever changes the end user makes to Word's Normal template and, moverover, your code ignores Word's Styles thereby increasing the difficulty of maintaining the output documents, increasing their file size, and making them more prone to corruption.

    Cheers
    Paul Edstein
    [MS MVP - Word]

    Wednesday, June 22, 2016 1:05 PM
  • Hi Rajesh121345,

    you had paste a code here and given a title "How to add table of content".

    did you had any problem with above mentioned code?

    if you want to add table of content then visit the link below.

    TablesOfContents.Add Method

    TablesOfContents.Add2000 Method

    TablesOfContents.AddOld Method

    TablesOfContents.MarkEntry Method

    Regards

    Deepak


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, June 23, 2016 8:31 AM
    Moderator
  • Besides using Word.Interop, you can also use .NET Word API to create TOC in Word document like below:

    Document doc = new Document();
    Section section = doc.AddSection();
    Paragraph para = section.AddParagraph();
    
    para.AppendTOC(1, 3);
    para1.AppendText("Head1");
    para1.ApplyStyle(BuiltinStyle.Heading1);
    
    Paragraph para2 = section.AddParagraph();
    para2.AppendText("Head2");
    para2.ApplyStyle(BuiltinStyle.Heading2);
    
    doc.UpdateTableOfContents();
    doc.SaveToFile("CreateTableOfContent.docx", FileFormat.Docx);


    Monday, June 27, 2016 3:43 AM
  • Hi Rajesh121345,

    since you created this thread you did not reply to the suggestions given by the community members.

    did your issue solved? if so would you like to share the suggestion with our community so that if some other member have same issue like you can also get solution by your post.

    if your issue is still exist then please let us know so that we can try to provide you further suggestions.

    Regards

    Deepak


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, June 27, 2016 7:49 AM
    Moderator