Write word form fields with DocumentFormat.OpenXML SDK

5.9k Views Asked by At

I am writing an application which should use DocumentFormat.OpenXML SDK for writing data to form fields in a word template. But I cannot find a property in the document-object of the SDK 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 fields is always null.

2

There are 2 best solutions below

0
On

You can do that by replacing this line:

if (field.LocalName == "Name")

with this one:

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

Besides, you can use the following code to put a text inside the form field element using the function SetFormFieldValue provided in the another SO answer:

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

See Write data into TextInput elements in docx documents with OpenXML 2.5 for the implementation of SetFormFieldValue

0
On

Is it possible that your document is using Custom Properties to fill the field of the form? Try to have a look at this MSDN page that explains how to read and manipulate custom properties.