creating word document using word template in c#

2.3k Views Asked by At

I am working on .net platform. I have created a word template(.dotx) and added mergefields in it. i am replacing merge field from database column values. Now i want to loop on merge field. for example :- i have merge fields named < DepartmentID > and < DepartmentName > . And i am getting data from database's table named "tblDepartment" which have two columns "DepID" and "DepName". this table have 5 rows. i want to loop on these mergefields.

i want to show file like this. before execute the docx file is :- < DepartmentID > < DepartmentName >

after code execute:- DepID DepName

                               1                 DotNet

                               2                 Java

                               3                 PHP

Here Is My Code:

        foreach (Word.Field myMergeField in wordDoc.Fields)
        {
            Word.Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;
            // ONLY GETTING THE MAILMERGE FIELDS
            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim().Replace("\"", "");
                if (fieldName == "DepartmentID")
                {
                    myMergeField.Select();
                    wordApp.Selection.TypeText("DepartmentID");
                }
                if (fieldName == "DepartmentName")
                {
                    EAccreditationEntities dbModel = new EAccreditationEntities();
                    var q = (from p in dbModel.Departments select p).ToList();
                    //here q has all data from database , have columns (ID and Name of Department)
                     myMergeField.Select();
                    wordApp.Selection.TypeText("DEPNAME");
                }
            }

And the problem is that , my document have five pages , merge fields on 5th page and sql query returns 5 rows. when i am executing my code ,it shows first record on 5th page, then 6,7,8,9 pages create with 1,2,3,4 pages content and on 10th page shows 2nd record and so on.... Whole process creates 25 pages document file.

But i want to show all data on 5th page only. and not want to create extra pages.

0

There are 0 best solutions below