是否有一种简单的方法来复制单词doc。使用C#进入另一个?

时间:2011-04-23 12:06:00

标签: c# ms-word copy office-interop paste

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

我发现这段代码没有给我任何错误,但它似乎没有做任何事情。它肯定没有复制到正确的单词doc。就是这样。

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

2 个答案:

答案 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);

答案 1 :(得分:1)

很高兴看到所有C#人员现在都在询问VBA开发人员自15年以来所回答的问题。如果您必须处理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,它允许使用可选参数。