如何使用c#填充word模板

时间:2013-05-12 09:30:12

标签: c# ms-word

我正在尝试填充具有mergefield的单词模板,当我运行应用程序时,它会从现有模板生成一个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();
    }

1 个答案:

答案 0 :(得分:2)

这里有一个简单的错误

if (fieldText.StartsWith("MERGEFIELD"))

该字段以空格开头,只需使用

即可
if (fieldText.StartsWith(" MERGEFIELD"))

或将修剪应用于fieldText

String fieldText = rngFieldCode.Text.Trim();