2015-02-24 76 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); 
      } 
     }