【问题标题】:Creating word add in with OpenXML to insert new MergeField使用 OpenXML 创建 word add in 以插入新的 MergeField
【发布时间】:2017-12-11 07:55:53
【问题描述】:

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

所以我在 ButtonClick 中有这段代码

// 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 的函数:

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 时,它什么也没做 感谢您的帮助。

【问题讨论】:

    标签: c# ms-word vsto openxml word-addins


    【解决方案1】:

    添加一个 try/catch,你可能会发现它无法打开文件,因为它当前正在编辑中。

    OpenXML SDK 是一个用于写入 Office 文件的库,无需通过 Office 的界面。但是您在尝试这样做的同时还使用了 Office 的界面,因此您实际上是在尝试同时采用两种方法。除非您先关闭文档,否则这将不起作用。

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

    Fields.Add(Range, Type, Text, PreserveFormatting)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多