2017-11-26 27 views
0

私はVSTOとOpenXMLを初めて使いました。Wordアドインをいくつか開発したいと思います。このアドインはOpenXMLを使用する必要があります。開いているドキュメントを編集することは可能ですか? たとえば、Word文書を開いたので、ボタンクリックでOpenXMLを使用してテキストを置き換えたいとします。OpenXMLで単語を追加する

私はこのコードを持っています。

var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName; 
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true); 

     //edit document using OpenXml here 

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

と私はOpenXMLの How to: Open and add text to a word processing document (Open XML SDK)

を使用してWordにテキストを追加するためにこれを見つけたが、私は彼らが一緒に働くようにする方法を見つけ出すことはできません。

誰でもこの手伝いをすることはできますか?ありがとう

答えて

0

これは私がそれを解決する方法である:

private void button1_Click(object sender, RibbonControlEventArgs e) 
     { 
      var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName; 

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


      OpenAndAddTextToWordDocument(fileFullName, "[USER_NAME]"); 


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

     public static void 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 new text. 
      DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); 
      Run run = para.AppendChild(new Run()); 
      run.AppendChild(new Text(txt)); 

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

    } 
0

このようなことができます。

public static void SearchAndReplace(string document) 
{ 
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) 
    { 
     string docText = null; 
     using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) 
     { 
      docText = sr.ReadToEnd(); 
     } 

     Regex regexText = new Regex("Hello world!"); 
     docText = regexText.Replace(docText, "Hi Everyone!"); 

     using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) 
     { 
      sw.Write(docText); 
     } 
    } 
} 

詳細については、この記事をお読みください。

https://msdn.microsoft.com/en-us/library/office/bb508261.aspx

+0

をうん、私はそれを見てきましたが、@Rainman –

+1

は 'それが仕事をdoes'tカントー私は私のコードでそれを実装するとき、それは仕事をdoes't 「それよりも詳細を私たちに伝える必要があります。 **具体的に**何が動作していないのですか?それはコンパイルされていませんか?もしそうなら、エラーは何ですか?それは実行されていませんか?それは実行されているが例外をスローしていますか?それは過剰なピザを注文していますか?他に何か? – mjwills