I have a word document contains a bookmark. I named it Template.docx and the bookmark name is DistributionHeader.
What I need to do is import the content from another file (Data.docx) to this file and the content should be placed at the bookmark.
Bellow is my code snippet
- Code: Select all
var dataFilePath = @"Data.docx";
var templateFilePath = @"Template.docx";
var outputFilePath = @"Output.docx";
var bookmarkName = "DistributionHeader";
//Load documents
var dataDocument = new Document();
dataDocument.LoadFromFile(dataFilePath);
var templateDocument = new Document();
templateDocument.LoadFromFile(templateFilePath);
//
//Import content from a document to another document
//Base on this document https://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/Document-Operation/Copy-Content-from-one-Word-Document-to-another-in-C-VB.NET.html
//The content will be imported to tempSection
//
Section tempSection = templateDocument.AddSection();
Paragraph paragraph = tempSection.AddParagraph();
foreach (Section section in dataDocument.Sections)
{
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
tempSection.Body.ChildObjects.Add(documentObject.Clone());
}
}
//Navigate to the bookmark
var bookmarkNavi = new BookmarksNavigator(templateDocument);
bookmarkNavi.MoveToBookmark(bookmarkName);
//Try to insert every content from the tempSection to the bookmark
foreach (Paragraph paragrapthToInsert in tempSection.Paragraphs)
{
bookmarkNavi.InsertParagraph(paragrapthToInsert.Clone() as Paragraph);
}
// Remove the unneccessary content
templateDocument.Sections.Remove(tempSection);
templateDocument.SaveToFile(outputFilePath);
If I remove the line
- Code: Select all
templateDocument.Sections.Remove(tempSection);
The content from the file Data.docx will display at the end of the file Output.
Otherwise, the Output file will not contain the file Data.docx.
Can someone help me on this.
Thank you very much