C# 如何用c语言填写word模板#

C# 如何用c语言填写word模板#,c#,ms-word,C#,Ms Word,我正在尝试填充具有mergefield的word模板,当我运行应用程序时,它会从现有模板生成word文件,但字段未填充。没有错误。我不知道为什么它对我不起作用 代码如下: protected void Button2_Click(object sender, EventArgs e) { //OBJECT OF MISSING "NULL VALUE" Object oMissing = System.Reflection.Missing.Val

我正在尝试填充具有mergefield的word模板,当我运行应用程序时,它会从现有模板生成word文件,但字段未填充。没有错误。我不知道为什么它对我不起作用

代码如下:

    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();