2

我正在尝试将所有元素从 word doc 复制到新的 word doc。当我尝试获取所有 ChildElements 时,我在此行“对于每个元素 As OpenXmlElement In templatedoc.MainDocumentPart.Document.Body.ChildElements”收到消息“对象引用未设置为对象的实例”

请帮忙

代码:

Dim containerElement = NewDocument.MainDocumentPart.Document.Descendants().FirstOrDefault()       

Dim clonedElements = New List(Of OpenXmlElement)

For Each element As OpenXmlElement In templatedoc.MainDocumentPart.Document.Body.ChildElements

         clonedElements.Add(element.Clone())

Next

containerElement.RemoveAllChildren()

containerElement.Append(clonedElements)
4

1 回答 1

0

谢谢男孩女孩们!

这是我的最终工作代码:

                ' Copy XML parts to define document
                NewDocument.AddPart(templatedoc.GetPartById("rId3"), "rId3")
                NewDocument.AddPart(templatedoc.GetPartById("rId2"), "rId2")

                '// Add a main document part. 
                Dim mainPart = NewDocument.AddMainDocumentPart()

                ' // Add a Body               
                mainPart.Document = New Document(New Body())

                'Copy Document XMLParts - must be in specific order
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId8"), "rId8")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId3"), "rId3")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId7"), "rId7")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId2"), "rId2")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId1"), "rId1")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId6"), "rId6")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId5"), "rId5")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId4"), "rId4")
                mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId9"), "rId9")


                '// Copy text from template document
                Dim containerElement = NewDocument.MainDocumentPart.Document.Descendants().FirstOrDefault()
                Dim clonedElements = New List(Of OpenXmlElement)

                Dim elementstocopy = templatedoc.MainDocumentPart.Document.Body.ChildElements

                For Each element As OpenXmlElement In elementstocopy
                    clonedElements.Add(element.Clone())
                Next

                containerElement.RemoveAllChildren()
                containerElement.Append(clonedElements)

                mainPart.Document.Save()
于 2012-09-13T10:49:58.160 回答