How to copy the content of one word document into another word document?

后端 未结 3 828
一整个雨季
一整个雨季 2021-01-16 16:47

I have a word document with some Text and Images. I want to copy the content of the word document into another word document using C#.

Thanks.

3条回答
  •  死守一世寂寞
    2021-01-16 17:16

    Below function will show you how to open - close and copy from word doc.

    using MsWord = Microsoft.Office.Interop.Word;
    private static void MsWordCopy()
        {
            var wordApp = new MsWord.Application();
            MsWord.Document documentFrom = null, documentTo = null;
    
            try
            {
                var fileNameFrom = @"C:\MyDocFile.docx";               
    
                wordApp.Visible = true;
    
                documentFrom = wordApp.Documents.Open(fileNameFrom, Type.Missing, true);
                MsWord.Range oRange = documentFrom.Content;
                oRange.Copy();
    
                var fileNameTo = @"C:\MyDocFile-Copy.docx";
                documentTo = wordApp.Documents.Add();
                documentTo.Content.PasteSpecial(DataType: MsWord.WdPasteOptions.wdKeepSourceFormatting);
                documentTo.SaveAs(fileNameTo);              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
    
            finally
            {
                if (documentFrom != null)
                    documentFrom.Close(false);
    
                if (documentTo != null)
                    documentTo.Close();
    
                if (wordApp != null)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
    
                wordApp = null;
                documentFrom = null;
                documentTo = null;
    
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    

提交回复
热议问题