简体   繁体   English

我如何用文档中的合并字段替换所有文本

[英]how can i replace all text with merge field in document

i have two 'DEMO' word 我有两个“ DEMO”字样

and i want replace that with mergefield 我想用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");

You're only doing one Find operation. 您仅执行一次Find操作。 Instead try while (rng.Find.Execute(...)) { ... } 而是尝试while (rng.Find.Execute(...)) { ... }

You can to use Open XML SDK 2.5 . 您可以使用Open XML SDK 2.5 You can to read office file as Big XML file, and then you can change what you want. 您可以将Office文件读取为Big XML文件,然后可以更改所需内容。

  1. You must to read Word file as MemoryStream 您必须将Word文件读取为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. 您可以使用Office文件执行所有操作。 (Word, Excel...) This my example. (Word,Excel ...)这是我的示例。 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. 您可以使用Open XML SDK 2.5 Productivity Tool读取所需的任何文件。 该程序将帮助您了解文件结构。 Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM