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.
You can do that by replacing this line:
with this one:
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:See Write data into TextInput elements in docx documents with OpenXML 2.5 for the implementation of
SetFormFieldValue