复制word doc中的所有元素

时间:2012-09-06 08:03:20

标签: asp.net vb.net ms-word openxml

我正在尝试将单词doc中的所有元素复制到新单词doc。当我尝试获取所有ChildElements时,我在此行上收到消息“对象引用未设置为对象的实例”“对于每个元素作为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)

1 个答案:

答案 0 :(得分: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()