Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace bookmark text in Word file using Open XML SDK

Tags:

I assume v2.0 is better... they have some nice "how to:..." examples but bookmarks don't seem to act as obviously as say a Table... a bookmark is defined by two XML elements BookmarkStart & BookmarkEnd. We have some templates with text in as bookmarks and we simply want to replace bookmarks with some other text... no weird formatting is going on but how do I select/replace bookmark text?

like image 592
Mr. Boy Avatar asked Jul 22 '10 11:07

Mr. Boy


People also ask

What is Documentformat Openxml?

The Open XML SDK provides tools for working with Office Word, Excel, and PowerPoint documents. It supports scenarios such as: - High-performance generation of word-processing documents, spreadsheets, and presentations. - Populating content in Word files from an XML data source.


2 Answers

Here's my approach after using you guys as inspiration:

  IDictionary<String, BookmarkStart> bookmarkMap =        new Dictionary<String, BookmarkStart>();    foreach (BookmarkStart bookmarkStart in file.MainDocumentPart.RootElement.Descendants<BookmarkStart>())   {       bookmarkMap[bookmarkStart.Name] = bookmarkStart;   }    foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)   {       Run bookmarkText = bookmarkStart.NextSibling<Run>();       if (bookmarkText != null)       {           bookmarkText.GetFirstChild<Text>().Text = "blah";       }   } 
like image 171
Mr. Boy Avatar answered Sep 22 '22 06:09

Mr. Boy


Replace bookmarks with a single content (possibly multiple text blocks).

public static void InsertIntoBookmark(BookmarkStart bookmarkStart, string text) {     OpenXmlElement elem = bookmarkStart.NextSibling();      while (elem != null && !(elem is BookmarkEnd))     {         OpenXmlElement nextElem = elem.NextSibling();         elem.Remove();         elem = nextElem;     }      bookmarkStart.Parent.InsertAfter<Run>(new Run(new Text(text)), bookmarkStart); } 

First, the existing content between start and end is removed. Then a new run is added directly behind the start (before the end).

However, not sure if the bookmark is closed in another section when it was opened or in different table cells, etc. ..

For me it's sufficient for now.

like image 39
cyberblast Avatar answered Sep 22 '22 06:09

cyberblast