如何使用c#填充word模板
本文关键字:word 模板 填充 何使用 | 更新日期: 2023-09-27 18:13:15
我试图填充具有合并字段的单词模板,当我运行应用程序时,它从现有模板生成一个单词文件,但字段未填充。没有错误。我不知道为什么它对我不起作用
代码如下:
protected void Button2_Click(object sender, EventArgs e)
{
//OBJECT OF MISSING "NULL VALUE"
Object oMissing = System.Reflection.Missing.Value;
Object oTemplatePath = "C:''Users''pca''Desktop''temp1.dotx";
Application wordApp = new Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Field myMergeField in wordDoc.Fields)
{
Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith("MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("''");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
// GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
fieldName = fieldName.Trim();
if (fieldName == "Name")
{
myMergeField.select();
wordApp.selection.TypeText("amal");
}
}
}
wordDoc.SaveAs("myfile1.docx");
wordApp.Documents.Open("myFile1.docx");
//wordApp.Application.Quit();
}
这里有一个简单的错误
if (fieldText.StartsWith("MERGEFIELD"))
字段以空格开头,用
修复if (fieldText.StartsWith(" MERGEFIELD"))
或对fieldText
应用修剪String fieldText = rngFieldCode.Text.Trim();