Replace bookmark text in Word file using Open XML SDK

前端 未结 11 2035
眼角桃花
眼角桃花 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条回答
  •  星月不相逢
    2020-12-01 08:50

    Replace bookmarks with a single content (possibly multiple text blocks).

    public static void InsertIntoBookmark(BookmarkStart bookmarkStart, string text)
    {
        OpenXmlElement elem = bookmarkStart.NextSibling();
    
        while (elem != null && !(elem is BookmarkEnd))
        {
            OpenXmlElement nextElem = elem.NextSibling();
            elem.Remove();
            elem = nextElem;
        }
    
        bookmarkStart.Parent.InsertAfter(new Run(new Text(text)), bookmarkStart);
    }
    

    First, the existing content between start and end is removed. Then a new run is added directly behind the start (before the end).

    However, not sure if the bookmark is closed in another section when it was opened or in different table cells, etc. ..

    For me it's sufficient for now.

提交回复
热议问题