Replace bookmark text in Word file using Open XML SDK

前端 未结 11 2014
眼角桃花
眼角桃花 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:38

    After a lot of hours, I have written this method:

        Public static void ReplaceBookmarkParagraphs(WordprocessingDocument doc, string bookmark, string text)
        {
            //Find all Paragraph with 'BookmarkStart' 
            var t = (from el in doc.MainDocumentPart.RootElement.Descendants()
                     where (el.Name == bookmark) &&
                     (el.NextSibling() != null)
                     select el).First();
            //Take ID value
            var val = t.Id.Value;
            //Find the next sibling 'text'
            OpenXmlElement next = t.NextSibling();
            //Set text value
            next.GetFirstChild().Text = text;
    
            //Delete all bookmarkEnd node, until the same ID
            deleteElement(next.GetFirstChild().Parent, next.GetFirstChild().NextSibling(), val, true);
        }
    

    After that, I call:

    Public static bool deleteElement(OpenXmlElement parentElement, OpenXmlElement elem, string id, bool seekParent)
    {
        bool found = false;
    
        //Loop until I find BookmarkEnd or null element
        while (!found && elem != null && (!(elem is BookmarkEnd) || (((BookmarkEnd)elem).Id.Value != id)))
        {
            if (elem.ChildElements != null && elem.ChildElements.Count > 0)
            {
                found = deleteElement(elem, elem.FirstChild, id, false);
            }
    
            if (!found)
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }
        }
    
        if (!found)
        {
            if (elem == null)
            {
                if (!(parentElement is Body) && seekParent)
                {
                    //Try to find bookmarkEnd in Sibling nodes
                    found = deleteElement(parentElement.Parent, parentElement.NextSibling(), id, true);
                }
            }
            else
            {
                if (elem is BookmarkEnd && ((BookmarkEnd)elem).Id.Value == id)
                {
                    found = true;
                }
            }
        }
    
        return found;
    }
    

    This code is working good if u have no empty Bookmarks. I hope it can help someone.

提交回复
热议问题