Write word form fields with DocumentFormat.OpenXML SDK
Asked Answered
D

2

6

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.

Decillion answered 9/6, 2015 at 10:18 Comment(1)
See #29288344Zinfandel
H
2

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

Hyoscyamine answered 25/3, 2017 at 21:42 Comment(0)
A
0

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.

Al answered 2/9, 2016 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.