Modifying Microsoft Office Word Content Control OpenXml


In my case I had a Microsoft Office Word document which contains content place controls which needs to be filled by specific data after specific business action.

The idea is to select all the descendants from type “SdtElement” which has a tag name specified and then compare it with the provided tag name.

Next, remove all the text from the content control and add our new value.

Sample code:

private void ModifyDocumentPlaceHolder(Document document, string tagName, string value)
        {
            // Find all placeholders with Tag name
            var placeHolders = document.MainDocumentPart.RootElement.
                Descendants<SdtElement>().
                Where(P => P.Elements<SdtProperties>().FirstOrDefault().
                    Elements<Tag>().FirstOrDefault() != null);

            // Select the required element by tag name
            var requiredPlaceHolder = placeHolders.FirstOrDefault(P =>
                P.Elements<SdtProperties>().FirstOrDefault().
                Elements<Tag>().FirstOrDefault().Val == tagName);

            // Remove all text from the place holder
            requiredPlaceHolder.Descendants<Text>().ToList().ForEach(
                delegate(Text textObj)
                {
                    textObj.Text =
 string.Empty;
                });

            // Add the required text
            requiredPlaceHolder.Descendants<Text>().FirstOrDefault().Text = value;

        }

I hope that helped

Ahmed

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s