Monday, April 04, 2011

How to delete items from Table of Content (TOC) by using Open XML SDK 2.0

 How to delete items from Table of Content (TOC) by using Open XML SDK 2.0

I was looking some way to update TOC after generating the word document from template, but I came to know that there are no way we can update the TOC as we do in MS Word design time (Update Table).

I found couple of articles saying you can create complete TOC runtime and this will work like a update TOC. You can see this example here http://openxmldeveloper.org/forums/thread/4680.aspx

But somehow I did not feel comfortable with this solution and also it does not works for me, may I could have spent much time on it.

Anyway I found simple solution for my requirement, my requirement was, I have predefined 
TOC on the word Template Like below


And now based on the heading deleted on the document I have to delete the same items from TOC, for that I can simply query TOC and delete it.

Name Space

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

C# Code

//This is hard coded variable to show only one item remove, but you can make function and make it generic for any items in TOC
string TOCItems = "Introduction";

//System.Xml.Linq.XElement TOC = null;
OpenXmlElement blocks = mainPart.Document.Descendants<DocPartGallery>()
.Where(p => p.Val.HasValue && (p.Val.Value == "Table of Contents")).FirstOrDefault();

 if (blocks != null)
 {
    while ((blocks != null) && !(blocks is SdtBlock))
    {
       blocks = blocks.Parent;
     }
       // This line you can use if you 
       //  need complete TOC from document
//TOC = new System.Xml.Linq.XElement("TOC", blocks.OuterXml);
   }

   var b = blocks.Descendants<Hyperlink>();

   foreach (Hyperlink block in b)
   {
     if (block.InnerText.Contains(TOCItems) == true)
      {
         // This block only to make sure this should not 
         // be the first element in TOC    
         if (tocName == "Executive Summary")
         {
            // This code will delete the item from 
            // TOC without Space      
            block.Remove();   
          }
          else
          {
// This code will delete the item from
// TOC with space
            block.Parent.Remove();
           }
        }
     }

Output will be


Reference:


No comments: