Inserting text after a bookmark in openxml

后端 未结 2 1795
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 00:00

I am looking for a way to insert some text after a bookmark in a word doc using openxml. So far, i have been able to locate the bookmark using the following:

var         


        
2条回答
  •  醉话见心
    2021-02-09 00:50

    using

    bookMarkToWriteAfter.Parent.InsertAfterSelf(run);
    

    you are trying to work with XML directly which is not always advisable with OpenXML.

    Try This..

        Body body = mainPart.Document.GetFirstChild();
        var paras = body.Elements();
    
        //Iterate through the paragraphs to find the bookmarks inside
        foreach (var para in paras)
        {
            var bookMarkStarts = para.Elements();
            var bookMarkEnds = para.Elements();
    
    
            foreach (BookmarkStart bookMarkStart in bookMarkStarts)
            {
                if (bookMarkStart.Name == bookmarkName)
                {
                    //Get the id of the bookmark start to find the bookmark end
                    var id = bookMarkStart.Id.Value;
                    var bookmarkEnd = bookMarkEnds.Where(i => i.Id.Value == id).First();
    
                    var runElement = new Run(new Text("Hello World!!!"));
    
                    para.InsertAfter(runElement, bookmarkEnd);
    
                }
            }
       }
       mainPart.Document.Save();
    

提交回复
热议问题