首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用OpenXML创建word外接程序以插入新MergeField

使用OpenXML创建word外接程序以插入新MergeField
EN

Stack Overflow用户
提问于 2017-12-11 15:55:54
回答 1查看 504关注 0票数 1

我是VSTO和OpenXML的新手,我想开发一个Word插件。这个插件应该使用OpenXML,插件应该将MergeField添加到文档中,我实际上可以使用ConsoleApp添加MergeField,但是我想将Word插件中的MergeField插入到当前打开的文档中。

所以我用ButtonClick编写了这段代码

代码语言:javascript
复制
// take current file location
            var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;

            Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);

            // function to insert new field here
            OpenAndAddTextToWordDocument(fileFullName, "username");




            Globals.ThisAddIn.Application.Documents.Open(fileFullName);

我创建了一个函数,它将添加新的MergeField:

代码语言:javascript
复制
public static DocumentFormat.OpenXml.Wordprocessing.Paragraph OpenAndAddTextToWordDocument(string filepath, string txt)
        {
            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
            WordprocessingDocument.Open(filepath, true);

            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;


            // add text

            string instructionText = String.Format(" MERGEFIELD  {0}  \\* MERGEFORMAT", txt);
            SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };

            Run run1 = new Run();

            RunProperties runProperties1 = new RunProperties();
            NoProof noProof1 = new NoProof();

            runProperties1.Append(noProof1);
            Text text1 = new Text();
            text1.Text = String.Format("«{0}»", txt);

            run1.Append(runProperties1);
            run1.Append(text1);

            simpleField1.Append(run1);

            DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
            paragraph.Append(new OpenXmlElement[] { simpleField1 });
            return paragraph;




        // Close the handle explicitly.
        wordprocessingDocument.Close();

但是有些东西在这里不起作用,当我使用add时,它不会做任何事情,谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2017-12-12 05:03:46

添加try/catch后,您可能会发现它无法打开该文件,因为该文件当前处于打开状态以供编辑。

Office是一个用于写入OpenXML文件的库,无需通过Office的接口。但是您试图在使用Office接口的同时做到这一点,因此您实际上是在尝试同时采用两种方法。除非您首先关闭文档,否则这不会起作用。

但是您可能想要使用VSTO。在VSTO中,每个文档都有一个Fields集合,您可以使用它来添加字段。

代码语言:javascript
复制
Fields.Add(Range, Type, Text, PreserveFormatting)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47748525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档