Enter word form fields using the DocumentFormat.OpenXML SDK

I am writing an application that should use the DocumentFormat.OpenXML SDK to write data to form fields in a word template. But I cannot find the property in the SDK document object where the form fields are stored.

I tried this code:

using (WordprocessingDocument document = WordprocessingDocument.Open("Path/To/document.dotx", true))
{
    document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
    MainDocumentPart mainPart = document.MainDocumentPart;

    var fields = mainPart.Document.Body.Descendants<FormFieldData>();

    foreach (var field in fields)
    {
        if (field.GetType() == typeof(FormFieldData))
        {
            if (field.LocalName == "Name")
            {
                Console.WriteLine("Hi!");
            }   
        }
     }
}

But the fields are always zero.

+4
source share
2 answers

Is it possible that your document uses custom properties to populate the form field? Try taking a look at this MSDN page that explains how to read and manage user properties.

0
source

You can do this by replacing this line:

if (field.LocalName == "Name")

with this:

if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Name"))

, , , SetFormFieldValue, SO:

        if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Name"))
        {
            TextInput text = field.Descendants<TextInput>().First();
            SetFormFieldValue(text, "Put some text inside the field");
        }

. TextInput docx OpenXML 2.5 SetFormFieldValue

0

All Articles