openxmlword-2007

How do you change the content of a content control in Word 2007 with OpenXml SDK 2.0?


About to go mad with this problem. I'm sure it's so simple I'm just missing it, but I cannot for the life of me find out how to change the content of a content control in Word 2007 with the OpenXml SDK v2.0 in C#.

I have created a Word document with a plain text content control. The tag for this control is "FirstName". In code, I'd like to open up the Word document, find this content control, and change the content without losing the formatting.

The solution I finally got to work involved finding the content control, inserting a run after it, then removing the content control as such:

using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(filePath, true)) {
MainDocumentPart mainDocumentPart = wordProcessingDocument.MainDocumentPart;
SdtRun sdtRun = mainDocumentPart.Document.Descendants<SdtRun>()
 .Where(run => run.SdtProperties.GetFirstChild<Tag>().Val == "FirstName").Single();

if (sdtRun != null) {
 sdtRun.Parent.InsertAfter(new Run(new Text("John")), sdtRun);
 sdtRun.Remove();
}

This does change the text, but I lose all formatting. Does anyone know how I can do this?


Solution

  • I found a better way to do the above using http://wiki.threewill.com/display/enterprise/SharePoint+and+Open+XML#SharePointandOpenXML-UsingWord2007ContentControls as a reference. Your results may vary but I think this will get you off to a good start:

    using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true)) {
        var sdtRuns = mainDocumentPart.Document.Descendants<SdtRun>()
            .Where(run => run.SdtProperties.GetFirstChild<Tag>().Val.Value == contentControlTagValue);
    
        foreach (SdtRun sdtRun in sdtRuns) {
            sdtRun.Descendants<Text>().First().Text = replacementText;
        }
    
        wordprocessingDocument.MainDocumentPart.Document.Save();
    }
    

    I think the above will only work for Plain Text content controls. Unfortunately, it doesn't get rid of the content control in the final document. If I get that working I'll post it.

    http://msdn.microsoft.com/en-us/library/cc197932.aspx is also a good reference if you want to find a rich text content control. This one talks about adding rows to a table that was placed in a rich text content control.