在OpenXml中使用项目符号复制文本

时间:2011-10-12 12:36:10

标签: .net vb.net openxml wordprocessingml

我有以下问题:

需要将文本从1个文字处理文档复制到另一个文字处理文档。在目标部件中插入文本时,无法始终访问源文档。该文本将被序列化并在以后检索。

我现在这样做的方法是复制段落元素,然后将它们附加到另一个文档中。除非涉及子弹,否则此工作正常。 子弹不会从源文件复制到目标文档。

以下是一些示例代码:

Public Sub SerializeParagraphsBetweenBookmark(ByVal stream As Stream)
    Dim wordDoc = WordprocessingDocument.Open(_fileLocation, True)
    Dim paragraphsFromBookmarks As IEnumerable(Of Paragraph)
    Using (wordDoc)
        paragraphsFromBookmarks = GetAllParagraphFromBookmarks(wordDoc)
    End Using
    SerializeParagraphsToFile(paragraphsFromBookmarks, stream)
End Sub

Private Sub SerializeParagraphsToFile(ByVal paragraphsFromBookmarks As IEnumerable(Of Paragraph), stream As Stream)
    ' the IEnumerable of paragraphs must be converted to an IEnumerable of strings before it can be converted
    Dim serializableIEnumerable = paragraphsFromBookmarks.Select(Function(x) x.OuterXml).ToList()
    Dim binSerializer As New BinaryFormatter()
    binSerializer.Serialize(stream, serializableIEnumerable)
End Sub

然后当我检索它们时,我将它们添加到目标文件中,如下所示:

Public Sub InsertParagraphsInDocument(paragraphs As IEnumerable(Of Paragraph))
    Dim wordDoc = WordprocessingDocument.Open(_fileLocation, True)
    Using (wordDoc)
        Dim rootElement = wordDoc.MainDocumentPart.RootElement
        Dim bookmark = rootElement.Descendants(Of BookmarkStart).FirstOrDefault(Function(x) x.Name.Value.Equals(_pasteBookmark))
        Dim paragraphsList = paragraphs.ToList()
        For i As Integer = paragraphsList.Count - 1 To 0 Step -1
            bookmark.Parent.InsertAfterSelf(paragraphsList(i))
        Next
    End Using
End Sub

代码没什么特别的,欢迎任何改进建议。

我知道项目符号存储在MainDocument部分的 NumberingDefinitionsPart 中,但我的问题是如何知道要在此NumberingDefinitionsPart中插入哪个AbstractNum和NumberingInstance?

1 个答案:

答案 0 :(得分:0)

我自己找到了答案,似乎我必须同步两个文件之间的编号定义部分。

我写了一个工具,这样做,如果有人有兴趣,请查看:http://www.lucbos.net/2011/11/wordprocessing-serialization-move.html