2017-12-11 3 views
1

저는 VSTO 및 OpenXML을 처음 사용했습니다. Word 추가 기능을 개발하고 싶습니다. 이 추가 기능은 OpenXML을 사용해야합니다. 추가 기능은 문서에 MergeField를 추가해야합니다. 실제로 ConsoleApp을 사용하여 MergeField를 추가 할 수 있지만 Word의 MergeField를 현재 열린 문서에 추가하려고합니다. 그래서새 MergeField를 삽입하기 위해 OpenXML을 사용하여 단어 추가하기

나는 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 인터페이스도 사용하면서 그렇게하려고 노력하고 있으므로 기본적으로 한 번에 두 가지 방법을 시도합니다. 처음 문서를 닫지 않으면이 기능이 작동하지 않습니다.

하지만 아마도 VSTO를 사용하고 싶을 것입니다. VSTO에서는 각 문서에 필드를 추가하는 데 사용할 수있는 Fields 컬렉션이 있습니다.

Fields.Add(Range, Type, Text, PreserveFormatting) 
관련 문제