2015-02-24 85 views
0

我想用Word Interop嘗試用另一個文檔的內容替換Word文檔中的TAG。word interop替換文檔內容的標籤

例如,我必須處理example.doc具有像#TAG#123456789#標籤然後我需要複製123456789.doc並粘貼內容在example.doc更換標籤#TAG#123456789#

文獻123456789.doc有其表,圖像和什麼。

到目前爲止,我可以在example.doc中找到標籤並獲取123456789.doc,但我沒有找到關於如何除文本替換之外的任何工作方法。從一開始

  1. 追加example.doc到標籤的開頭:

    我想到的是一種新的方法,通過附加的使用範圍類似這樣的文件部分生成一個新文件。

  2. 附加123456789.doc
  3. example.doc的其餘部分從標籤的末尾附加到文檔的末尾。
+0

我定義在文件的範圍內1'Microsoft.Office.Interop.Word.Range RNG = document.Range(參照docStart,REF docEnd);'我選擇並複製整個第二個文檔:'object start = SubDoc.Content.Start; object end = SubDoc.Content.End; SubDoc.Range(ref start,ref end).Copy();'我複製範圍1中的內容:'rng.Paste();'保存文檔:'document.Save();'但是,無法複製圖像,我該怎麼辦? 對不起,但無法設法在評論中添加回車...... – 2015-02-24 14:46:36

+0

重複的帖子 – 2015-02-24 14:53:04

+0

如果我將目標範圍設置爲文檔結尾'docStart = document.Content.End - 1;對象docEnd = document.Content.End;'當我粘貼'Microsoft.Office.Interop.Word.Range rng = document.Range(ref docStart,ref docEnd); rng.Paste();'它粘貼所有包括圖像。 如果我選擇範圍來代替一個單詞ej:'object docStart = document.Content.Words [i - 8] .Start;對象docEnd = document.Content.Words [i] .End;'當我做同樣的粘貼時,它會粘貼第一個單詞。 – 2015-02-24 15:43:24

回答

0

看起來像你接近解決方案。當您找到該標籤並在文檔中選擇它時,可以使用WordApp.Selection.InsertFile()方法將另一個文檔中的內容插入到該選擇中。

確保首先進行選擇很重要。

實施例方法:

 /// <summary> 
     /// This method adds a file to the Word.ApplicationClass object's current selection. 
     /// Has been tested with word (*.doc)documents but not with other office files. 
     /// Other files may work also with this method. 
     /// Tested with the Microsoft 9.0 Object Library (COM) 
     /// </summary> 
     /// <param name="WordApp">The Word.ApplicationClass object</param> 
     /// <param name="DirLocation">A string that contains the file directory location.</param> 
     /// <param name="FileName">A string that contains the file name within the directory location.</param> 
     public static void InsertFile(Word.ApplicationClass WordApp, string DirLocation, string FileName) 
     { 
      try 
      { 
       object j_NullObject = System.Reflection.Missing.Value; 

       WordApp.Selection.InsertFile(DirLocation + FileName, ref j_NullObject, ref j_NullObject, ref j_NullObject, ref j_NullObject); 
      } 

      //An Exception will occur when the Directory location and filename does not exist. 
      //An Exception may also occur when the Word.ApplicationClass has no Selection to add 
      //the file to. 
      catch (Exception e) 
      { 
       //show the user the error message 
       MessageBox.Show(e.Message); 

       //log the error 
       //ErrorLog.LogError(e); 
      } 
     }