2017-12-11 11 views
1

私はVSTOとOpenXMLを初めて使いました。Wordアドインを開発したいと思います。このアドインではOpenXMLを使用する必要があります。アドインではドキュメントにMergeFieldを追加する必要がありますが、実際にはConsoleAppを使用してMergeFieldを追加できますが、WordのMergeFieldを現在開いているドキュメントに追加します。OpenXMLで単語を追加して新しい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(); 

をしかし、私は中に追加使用するとき何かが、ここで働いていませんそれは何もしない 助けをありがとう。

答えて

0

try/catchを追加すると、現在開いているので編集できないことがあります。

OpenXML SDKは、のOfficeファイルに書き込むためのライブラリであり、はOfficeのインターフェイスを経由しません。しかし、Officeのインターフェイスも使用しながらそうしようとしているので、本質的に2つのアプローチを一度に取ろうとしています。最初に文書を閉じるまで、これは機能しません。

しかし、おそらくあなたがしたいことは、VSTOを使用することです。 VSTOでは、各ドキュメントにフィールドを追加するために使用できるFieldsコレクションがあります。

Fields.Add(Range, Type, Text, PreserveFormatting) 
関連する問題