简体   繁体   中英

How do I find plain-text content controls within a .docx file and replace the text within using the OpenXML SDK?

I'm working on a program that needs to output data to a Word document, in which I've placed plain-text content controls which are tagged. Basically, I'm after writing the following method (using C#)...

public static void SetContentControlText(WordprocessingDocument document, string contentControlTag, string text)
{
    // TODO: Implement this method...
}

The method should be able to fill in all plain-text content controls with the specified tag, regardless of their position within the structure of the document (ie it should be able to find the content controls in the main body of the document as well as inside tables .etc.).

Thanks in advance!

After doing some digging around, I found / adapted the following solution...

public static int SetContentControlText(
    this WordprocessingDocument document,
    Dictionary<string, string> values)
{
    if (document == null) throw new ArgumentNullException("document");
    if (values == null) throw new ArgumentNullException("values");

    int count = 0;

    foreach (SdtElement sdtElement in document.MainDocumentPart.Document.Descendants<SdtElement>())
    {
        string tag = sdtElement.SdtProperties.Descendants<Tag>().First().Val;
        if ((tag != null) && values.ContainsKey(tag))
        {
            sdtElement.Descendants<Text>().First().Text = values[tag] ?? string.Empty;
            sdtElement.Descendants<Text>().Skip(1).ToList().ForEach(t => t.Remove());

            count++;
        }
    }

    return count;
}

The method takes in the document and a dictionary of tag/value pairs, and returns the number of content controls that were set!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM