2011-04-23 80 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); 
相關問題