Replace bookmark text in Word file using Open XML SDK

前端 未结 11 2037
眼角桃花
眼角桃花 2020-12-01 08:24

I assume v2.0 is better... they have some nice \"how to:...\" examples but bookmarks don\'t seem to act as obviously as say a Table... a bookmark is defined by two

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 08:37

    The accepted answer and some of the others make assumptions about where the bookmarks are in the document structure. Here's my C# code, which can deal with replacing bookmarks that stretch across multiple paragraphs and correctly replace bookmarks that do not start and end at paragraph boundaries. Still not perfect, but closer... hope it's useful. Edit if you find more ways to improve it!

        private static void ReplaceBookmarkParagraphs(MainDocumentPart doc, string bookmark, IEnumerable paras) {
            var start = doc.Document.Descendants().Where(x => x.Name == bookmark).First();
            var end = doc.Document.Descendants().Where(x => x.Id.Value == start.Id.Value).First();
            OpenXmlElement current = start;
            var done = false;
    
            while ( !done && current != null ) {
                OpenXmlElement next;
                next = current.NextSibling();
    
                if ( next == null ) {
                    var parentNext = current.Parent.NextSibling();
                    while ( !parentNext.HasChildren ) {
                        var toRemove = parentNext;
                        parentNext = parentNext.NextSibling();
                        toRemove.Remove();
                    }
                    next = current.Parent.NextSibling().FirstChild;
    
                    current.Parent.Remove();
                }
    
                if ( next is BookmarkEnd ) {
                    BookmarkEnd maybeEnd = (BookmarkEnd)next;
                    if ( maybeEnd.Id.Value == start.Id.Value ) {
                        done = true;
                    }
                }
                if ( current != start ) {
                    current.Remove();
                }
    
                current = next;
            }
    
            foreach ( var p in paras ) {
                end.Parent.InsertBeforeSelf(p);
            }
        }
    

提交回复
热议问题