In daily office work or enterprise-level document processing, we often need to copy content from Word documents — for example, merging core chapters from multiple documents, extracting specified paragraphs or tables, and backing up key parts of a document. Manual copying is not only inefficient but also prone to formatting loss. Automating the copy process via code ensures complete formatting retention and supports batch processing, greatly improving work efficiency.
This article uses the free library Free Spire.Doc for .NET to detail how to copy Word content in C#, covering common scenarios including copying an entire document, copying specified paragraphs, and copying content from a specified section. The library does not require Microsoft Office to be installed and provides a simple and easy-to-use API.
Installation Command (NuGet Package Manager Console):
Install-Package FreeSpire.Doc
1. Basic Scenario: Copy the Entire Word Document
This is the most direct scenario, such as copying all content (text, images, tables, formatting, etc.) from a source document completely into a new or existing document. The Clone() method can be used to achieve a deep copy.
using System;
using Spire.Doc;
namespace CopyWholeWordContent
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. Load the source document
Document sourceDoc = new Document();
sourceDoc.LoadFromFile(@"C:\Users\Administrator\Desktop\SourceDocument.docx");
// 2. Clone the source document (create an independent copy)
Document targetDoc = sourceDoc.Clone();
// 3. Save the target document
targetDoc.SaveToFile("CopiedFullDocumentContent.docx", FileFormat.Docx);
// Release resources
sourceDoc.Close();
targetDoc.Close();
Console.WriteLine("Full document content copied successfully!");
// Optional: Open the generated document to view the result
System.Diagnostics.Process.Start("CopiedFullDocumentContent.docx");
}
catch (Exception ex)
{
Console.WriteLine($"Copy failed: {ex.Message}");
}
}
}
}
Key Notes:
- The
Clone()method fully copies all content and formatting of the document to create an independent new document. Modifications to the copy will not affect the source document. -
try-catchexception handling is added to catch common issues such as invalid file paths, insufficient permissions, and corrupted documents, enhancing program robustness. - The
Close()method releases resources promptly to avoid file locking.
2. Advanced Scenario: Copy Specified Paragraph
Sometimes we only need to extract certain paragraphs (such as abstracts or conclusions) from a document and append them to the end of another document. The following code shows how to extract a paragraph at a specified index from the source document, preserve its full formatting (font, size, color, etc.), and add it to the last section of the target document.
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace CopySpecificParagraphs
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. Load the source document
Document sourceDoc = new Document();
sourceDoc.LoadFromFile(@"C:\Users\Administrator\Desktop\source.docx");
// 2. Extract the paragraph at the specified index from the source document (zero-based index; here the 9th paragraph)
Paragraph para = sourceDoc.Sections[0].Paragraphs[8];
// 3. Load the target document (existing document)
Document targetDoc = new Document();
targetDoc.LoadFromFile(@"C:\Users\Administrator\Desktop\target.docx");
// 4. Get the last section of the target document (add the paragraph to the end of this section)
Section lastSection = targetDoc.LastSection;
// 5. Clone and add the specified paragraph (Clone() creates an independent copy)
lastSection.Paragraphs.Add((Paragraph)para.Clone());
// 6. Save the target document
targetDoc.SaveToFile("CopyParagraphs.docx", FileFormat.Docx2016);
// 7. Release resources
sourceDoc.Dispose();
targetDoc.Dispose();
Console.WriteLine("Specified paragraph copied successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Copy failed: {ex.Message}");
}
}
}
}
Key Notes:
-
Index Note: Sections and paragraphs in a Word document use zero-based indexing.
Sections[0]represents the first section, andParagraphs[8]represents the 9th paragraph in that section. Adjust the index according to your actual document. -
Insertion Position: Use
LastSectionto get the last section of the target document and append the paragraph to the end of the document. To insert at a specified position, useSections[index]to locate the target section. -
Clone()Method: The core method that creates an independent copy of the paragraph, preventing subsequent changes to the source document from affecting the copied content. - Exception handling covers common errors such as index out of range and file not found.
3. Advanced Scenario: Copy a Specified Section
When you need to copy an entire section (including all elements such as paragraphs, tables, images, etc.) to the target document, you can achieve fine-grained control by iterating through the child objects of the section. This method is more flexible than copying the entire section directly and allows you to skip certain elements as needed.
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace CopySpecificSection
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. Load the source document
Document sourceDoc = new Document();
sourceDoc.LoadFromFile(@"C:\Users\Administrator\Desktop\source.docx");
// 2. Extract the specified section from the source document (example: extract the 1st section, index 0)
Section sourceSection = sourceDoc.Sections[0];
// 3. Load the target document
Document targetDoc = new Document();
targetDoc.LoadFromFile(@"C:\Users\Administrator\Desktop\target.docx");
// 4. Get the last section of the target document (add content to the end of this section)
Section lastSection = targetDoc.LastSection;
// 5. Iterate through all child objects in the source section body (paragraphs, tables, images, etc.), clone and add them to the target section
foreach (DocumentObject obj in sourceSection.Body.ChildObjects)
{
lastSection.Body.ChildObjects.Add(obj.Clone());
}
// 6. Save the document and release resources
targetDoc.SaveToFile("CopySection.docx", FileFormat.Docx2019);
sourceDoc.Dispose();
targetDoc.Dispose();
Console.WriteLine("Specified section content copied successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Copy failed: {ex.Message}");
}
}
}
}
Code Explanation:
-
sourceSection.Body.ChildObjects: TheBodyproperty of a section contains all visible content of that section (paragraphs, tables, images, etc.), and theChildObjectscollection provides access to these elements. -
Loop & Clone: Each child object is cloned and added to the
ChildObjectscollection of the target section, preserving the format and content of each element completely. - Exception handling ensures program stability.
4. Summary and Notes
Using the three methods above, you can flexibly handle various Word document copying tasks without manual operations, greatly improving processing efficiency. Please note the following points:
- File Paths: Replace the file paths in the code with your actual paths. Absolute paths are recommended, or ensure relative paths are correct.
- Index Out of Range: When extracting specified paragraphs or sections, make sure the index is within a valid range to avoid exceptions.
-
Resource Release: Call
Dispose()orClose()in time after operations to release resources and avoid file locking. -
Format Preservation: The
Clone()method is key to retaining the original format. Do not directly reference the original object. - Batch Processing: The above code can be slightly modified to loop through multiple documents for batch copying.
Top comments (0)