2011-04-23 86 views
1

如何复制一个word文档的内容并将其插入另一个使用C#的预先存在的word文档中。我看了一下,但一切看起来很复杂(我是一个新手)。当然,必须有一个简单的解决方案?有没有一种简单的方法来复制单词文档。到另一个使用C#?

我发现这个代码给了我没有错误,但它似乎没有做任何事情。这当然不是复制到正确的单词文档。这样说吧。

Word.Application oWord = new Word.Application(); 

Word.Document oWordDoc = new Word.Document(); 
Object oMissing = System.Reflection.Missing.Value; 
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 

oWordDoc.ActiveWindow.Selection.WholeStory(); 
oWordDoc.ActiveWindow.Selection.Copy(); 

oWord.ActiveDocument.Select(); 
oWordDoc.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault); 

P.S这些字文档是.DOC

+0

任何答案?这个代码是垃圾还是...? – toby 2011-04-23 12:18:51

+0

你想将两个单词文档合并为单个文件吗? – 2011-04-23 14:37:12

+0

哪种文件格式? .doc或.docx? – 2013-01-25 10:18:19

回答

1

这很有趣,看到所有的C#家伙现在问自15年VBA开发者已经回答的问题。如果您必须处理Microsoft Office自动化问题,那么在VB 6和VBA代码示例中进行挖掘是值得的。

对于“没有任何反应”这一点很简单:如果通过自动化启动Word,则必须将应用程序也设置为可见。如果你运行你的代码,它会工作,但Word仍然是一个不可见的实例(打开Windows任务管理器来查看它)。

对于“简单解决方案”这一要点,您可以尝试使用该范围的InsertFile方法在给定范围内插入文档,例如,像这样:

 static void Main(string[] args) 
    { 

     Word.Application oWord = new Word.Application(); 
     oWord.Visible = true; // shows Word application 

     Word.Document oWordDoc = new Word.Document(); 
     Object oMissing = System.Reflection.Missing.Value; 
     oWordDoc = oWord.Documents.Add(ref oMissing); 
     Word.Range r = oWordDoc.Range(); 
     r.InsertAfter("Some text added through automation!"); 
     r.InsertParagraphAfter(); 
     r.InsertParagraphAfter(); 
     r.Collapse(Word.WdCollapseDirection.wdCollapseEnd); // Moves range at the end of the text 
     string path = @"C:\Temp\Letter.doc"; 
     // Insert whole Word document at the given range, omitting page layout 
     // of the inserted document (if it doesn't contain section breakts) 
     r.InsertFile(path, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

    } 

注:我在这个例子中使用框架4.0,它允许可选参数。

2
 Word.Application oWord = new Word.Application(); 

     Word.Document oWordDoc = new Word.Document(); 
     Object oMissing = System.Reflection.Missing.Value; 
     object oTemplatePath = @"C:\\Documents and Settings\\Student\\Desktop\\ExportFiles\\" + "The_One.docx"; 
     oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 
     oWordDoc.ActiveWindow.Selection.WholeStory(); 
     oWordDoc.ActiveWindow.Selection.Copy(); 
     oWord.ActiveDocument.Select(); 
     // The Visible flag is what you've missed. You actually succeeded in making 
     // the copy, but because 
     // Your Word app remained hidden and the newly created document unsaved, you could not 
     // See the results. 
     oWord.Visible = true; 
     oWordDoc.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault); 
相关问题