使用open xml在word中插入合并字段

时间:2013-11-12 11:39:28

标签: ms-word openxml

我想将合并字段插入现有的单词doc。能够创建合并字段的xml元素,但不确定如何将其附加到文档。以下是我的代码

Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;

从上面我将获得活动文件

string instructionText = String.Format(" MERGEFIELD  {0}  \\* MERGEFORMAT", cmbType.Text + "__" + cmbField.Text);
            SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
            DocumentFormat.OpenXml.Wordprocessing.Run run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();
            RunProperties runProperties1 = new RunProperties();
            NoProof noProof1 = new NoProof();
            runProperties1.Append(noProof1);
            Text text1 = new Text();
            text1.Text = String.Format("«{0}»", cmbType.Text + "__" + cmbField.Text);
            run1.Append(runProperties1);
            run1.Append(text1);
            simpleField1.Append(run1);
            DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
            paragraph.Append(new OpenXmlElement[] { simpleField1 });

这是创建一个段落。现在我如何将此段落元素附加到wrdDoc

1 个答案:

答案 0 :(得分:-1)

Word.MailMerge wrdMailMerge;
            Word.Selection wrdSelection;
            Word.MailMergeFields wrdMergeFields;
            Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;
            Microsoft.Office.Interop.Word.Application wrdApp = Globals.ThisAddIn.Application;

            wrdSelection = wrdApp.Selection;
            wrdMailMerge = wrdDoc.MailMerge;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdSelection.ParagraphFormat.Alignment =
            Word.WdParagraphAlignment.wdAlignParagraphJustify;
            wrdMergeFields.Add(wrdSelection.Range, fieldname);