Free Support Forum -

Insert the content of other Documents in a dynamic generated Document


I am trying to insert the content of different Word Documents in my "master" document. I build a Table from the scratch using a Documentbuilder and it's methods StartTable, InsertCell and EndRow. How can i add the content of another Word Document to the actual cell of the Table.

I saw your Wiki article and I found it very helpful, but the posted code only shows how entire Sections can be added to the end of the document. I tried to adapt the code to my needs, but the result is always the same. The desired nodes from the source documents are added to the end of the "master" document.

My code looks as follows:

For Each srcSection As Section In mySourceDocument
For Each srcBody As Object In srcSection.ChildNodes
For Each srcChildNode As Object In srcBody.ChildNodes
Dim dstChildNode As Node = oDocumentBuilder.Document.ImportNode(srcChildNode, True, ImportFormatMode.UseDestinationStyles)



Please try using the following method:


''' Inserts content of the external document after the specified node.


''' Node in the destination document where the external document content should be inserted.

''' Document to insert.

Public Sub InsertDocument(ByVal node As Node, ByVal doc As Document)

Dim dstDoc As Document = node.Document

Dim insertedSection As Section

Dim index As Integer = node.ParentNode.ChildNodes.IndexOf(node) + 1

For Each section As Section In doc.Sections

insertedSection = CType(dstDoc.ImportNode(section, True, ImportFormatMode.KeepSourceFormatting), Section)

For Each insertedNode As Node In insertedSection.Body.ChildNodes

' Only Paragraph or Table nodes can be inserted into Cell or Shape

If TypeOf insertedNode Is Paragraph OrElse TypeOf insertedNode Is Table Then

' Do not insert node if it is a last empty paragarph in the section.

If TypeOf insertedNode Is Paragraph AndAlso insertedNode Is section.Body.LastChild AndAlso insertedNode.ToTxt().Equals(String.Empty) Then

Exit For

End If

node.ParentNode.ParentNode.ChildNodes.Insert(index, insertedNode.Clone(True))

End If

Next insertedNode

Next section

End Sub

Best regards,

Thank you for your quick answer. The only problem that remains is how to find the reference of the node in the destination document. How can i obtain the reference to the last added tablecell when I use the DocumentBuilders "InsertCell" method?



The DocumentBuilder.InsertCell method returns the reference to the cell node that was just inserted.