amal
amal

Reputation: 31

how to fill word template using c#

i am trying to fill word template that has mergefield and when i run the application it generates a word file from an existing template but the fields are not filled. There are no errors . I donot Know why it does not work with me

and here is the code :

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

Upvotes: 3

Views: 7623

Answers (1)

Steve
Steve

Reputation: 216343

You have a simple error here

if (fieldText.StartsWith("MERGEFIELD"))

The field starts with a space, fix simply with

if (fieldText.StartsWith(" MERGEFIELD"))

or apply a trim to your fieldText

String fieldText = rngFieldCode.Text.Trim();

Upvotes: 2

Related Questions