2014-07-08 100 views
2

我已經通過論壇在這裏使用C#將一個word文檔的內容複製到另一個word文檔。 Copy text from word file to a new word使用C#將一個word文檔中的特定頁面複製到另一個word文檔中

我使用了第二種解決方案。 這部分照顧複製的整個文件中使用的格式一起,

static MSWord.Document CopyToNewDocument(MSWord.Document document) 
{ 
document.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Copy(); 
var newDocument = document.Application.Documents.Add(); 
newDocument.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Paste(); 
return newDocument; 
} 

現在我想指定頁面範圍,從用戶,比如開始頁碼&結束頁碼,然後選擇複製獨自範圍到另一個Word文檔保存格式一起.. 在任何幫助,這將不勝感激.....

回答

2

你可能想看看http://social.msdn.microsoft.com/Forums/office/en-US/e48b3126-941d-490a-85ee-e327bbe7e81b/convert-specific-word-pages-to-pdf-in-c?forum=worddev

它展示瞭如何從aw獲取特定範圍的頁面ord文件(保存格式)。

相關部分(如果鏈接的頁面消失):

打開Word的一個實例。

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); 

並加載您的文檔。打開文件後,您必須準備好您的選擇範圍。 Count和count2是您在特例中提供的頁碼。

object what = WdGoToItem.wdGoToPage; 
    object which = WdGoToDirection.wdGoToFirst; 
    object count = 1; 
    Range startRange = word.Selection.GoTo(ref what, ref which, ref count, ref oMissing); 
    object count2 = (int)count + 3; 
    Range endRange = word.Selection.GoTo(ref what, ref which, ref count2, ref oMissing); 
    endRange.SetRange(startRange.Start, endRange.End - 1); 
    endRange.Select(); 

Selection.Copy()然後將所選頁面複製到剪貼板,同時保留格式。

word.Selection.Copy(); 

來源的其餘部分創建一個新的文檔,在其中粘貼您的選擇。

word.Documents.Add(); 
    word.Selection.Paste(); 

    object outputFileName = "d:\\test1.doc"; 
    object fileFormat = WdSaveFormat.wdFormatDocument97; 

    word.ActiveDocument.SaveAs(ref outputFileName, 
     ref fileFormat, ref oMissing, ref oMissing, 
     ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
     ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
     ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

我希望這會有所幫助。

+0

嗨@Thorias ..首先,非常感謝這個解決方案..這似乎工作,除了我有兩個說明。 1.我不知道爲什麼以及如何使用這個 對象what = WdGoToItem.wdGoToPage; object which = WdGoToDirection.wdGoToFirst; 2.格式將保留在目標文檔中,但每個頁面都會添加更多空格,並且頁眉/頁腳會丟失。 在我提到的解決方案論壇中,整個文檔被複制,包括格式和頁眉/頁腳 任何解決方法在此實現相同? 同樣,非常感謝您... – user3816807

+0

@ user3816807 Hi.WdGoToItem.wdGoToPage和WdGoToDirection.wdGoToFirst是Selection.Goto使用的枚舉,以便它知道您希望選擇的起點。在這種情況下,Selection.Goto將在由'count'指定的頁面頂部設置開始範圍。我昨天跑了一個簡短的測試,並沒有問題的頁眉/頁腳缺少或額外的空間添加到頁面。對不起,幫不了你。 – Thorias

相關問題