我正在编写一个应用程序,它应该使用 DocumentFormat.OpenXML SDK 来写入数据以形成 Word 模板中的字段。但是我在存储表单字段的 SDK 的文档对象中找不到属性。
我试过这段代码:
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!");
}
}
}
}
但字段始终为空。
最佳答案
你可以通过替换这一行来做到这一点:
if (field.LocalName == "Name")
用这个:
if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Name"))
此外,您可以使用以下代码将文本放入表单字段元素中,使用另一个 SO 答案中提供的函数 SetFormFieldValue
:
if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Name"))
{
TextInput text = field.Descendants<TextInput>().First();
SetFormFieldValue(text, "Put some text inside the field");
}
参见 Write data into TextInput elements in docx documents with OpenXML 2.5用于SetFormFieldValue
关于c# - 使用 DocumentFormat.OpenXML SDK 编写 word 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729233/