0

i have two 'DEMO' word

and i want replace that with mergefield

but just one 'DEMO' was changed using my code...

how can i replace text with field??

thanks

        Application app = new Application();
        Document word = new Document();

        word = app.Documents.Add(ref path, ref missing, ref missing, ref missing);

        object objType = WdFieldType.wdFieldMergeField;

        object hashVal = null;
        Hashtable hash = new Hashtable();

        hash.Add("DEMO", "mergefield11111");


        foreach (object s in hash.Keys)
        {

            Range rng = app.ActiveDocument.Content;
            Find findObject = app.Selection.Find;

            object ff = s;
            hashVal = hash[s];       

            findObject.Text = ff.ToString();
            findObject.ClearFormatting();
            if (rng.Find.Execute(ref ff,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, WdReplace.wdReplaceOne, ref missing, ref missing,
            ref missing, ref missing))
            {
                Field field = app.Selection.Fields.Add(app.Selection.Range, ref objType, ref hashVal, ref missing);
            }
        }
        app.Documents.Open("test1.docx");
Hee
  • 73
  • 1
  • 9
  • If you're blocked, you could try out the library I created that does just that (replacing values, or loops and conditions : https://github.com/open-xml-templating/docxtemplater) – edi9999 Jul 06 '16 at 15:21

2 Answers2

0

You're only doing one Find operation. Instead try while (rng.Find.Execute(...)) { ... }

Chris
  • 3,400
  • 1
  • 27
  • 41
0

You can to use Open XML SDK 2.5. You can to read office file as Big XML file, and then you can change what you want.

  1. You must to read Word file as MemoryStream
 public byte[] DocumentGenerator(String templatePath)
    {
        byte[] buffer;
        using (MemoryStream stream = new MemoryStream())
        {
            buffer = System.IO.File.ReadAllBytes(templatePath);
            stream.Write(buffer, 0, buffer.Length);
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
            {
               //Get list bookmarks
                var listBookMarks = wordDocument.MainDocumentPart.Document.Descendants<BookmarkStart>().ToList();
                //Get list Merge Fields
                var listMergeFields = wordDocument.MainDocumentPart.Document.Descendants<FieldCode>().ToList();
                //Do some code
                wordDocument.Close();
            }
            buffer = stream.ToArray();
        }

        return buffer;
    }
  1. Then, You Can change text, add Paragraph, add Table or other. You can do everything with your Office file. (Word, Excel...) This my example. I try to add Bullet List on my Bookmarks field:
            if (bookmark != null)
        {
            var parent = bookmark.Parent;   // bookmark's parent element
            var childEllement = parent.Elements<Run>().Last();
            var lastChild = childEllement.LastChild;
            childEllement.RemoveChild(lastChild);


            foreach (var itemChild in groupList)
            {

                Paragraph paragraph1 = new Paragraph();
                ParagraphProperties paragraphProperties = new ParagraphProperties();
                ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
                Tabs tabs = new Tabs();
                TabStop tabStop1 = new TabStop() { Val = TabStopValues.Left, Position = 284 };

                tabs.Append(tabStop1);
                SpacingBetweenLines spacingBetweenLines1 = new SpacingBetweenLines() { After = "120", Line = "360", LineRule = LineSpacingRuleValues.Auto };
                Indentation indentation1 = new Indentation() { Left = "0", FirstLine = "0" };
                Justification justification = new Justification() { Val = JustificationValues.Both };

                ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();

                paragraphProperties.Append(paragraphStyleId1);
                paragraphProperties.Append(tabs);
                paragraphProperties.Append(spacingBetweenLines1);
                paragraphProperties.Append(indentation1);
                paragraphProperties.Append(justification);
                paragraphProperties.Append(paragraphMarkRunProperties1);
                Run run1 = new Run();
                RunProperties runProperties1 = new RunProperties();

                Bold bold2 = new Bold();
                FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };

                runProperties1.Append(bold2);
                runProperties1.Append(fontSizeComplexScript2);
                Text text1 = new Text();
                text1.Text = "- " + itemChild + ";";
                run1.Append(runProperties1);
                run1.Append(text1);
                paragraph1.Append(paragraphProperties);
                paragraph1.Append(run1);
                parent.InsertAfterSelf(paragraph1);
            }
        }
  1. You can read any file what you want with Open XML SDK 2.5 Productivity Tool This program will help you understand the file structure. Good Luck!
Paweł Groński
  • 567
  • 1
  • 6
  • 17