Replace bookmark text in Word file using Open XML SDK

前端 未结 11 1993
眼角桃花
眼角桃花 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
    2020-12-01 08:45

    I just figured this out 10 minutes ago so forgive the hackish nature of the code.

    First I wrote a helper recursive helper function to find all the bookmarks:

    private static Dictionary FindBookmarks(OpenXmlElement documentPart, Dictionary results = null, Dictionary unmatched = null )
    {
        results = results ?? new Dictionary();
        unmatched = unmatched ?? new Dictionary();
    
        foreach (var child in documentPart.Elements())
        {
            if (child is BookmarkStart)
            {
                var bStart = child as BookmarkStart;
                unmatched.Add(bStart.Id, bStart.Name);
            }
    
            if (child is BookmarkEnd)
            {
                var bEnd = child as BookmarkEnd;
                foreach (var orphanName in unmatched)
                {
                    if (bEnd.Id == orphanName.Key)
                        results.Add(orphanName.Value, bEnd);
                }
            }
    
            FindBookmarks(child, results, unmatched);
        }
    
        return results;
    }
    

    That returns me a Dictionary that I can use to part through my replacement list and add the text after the bookmark:

    var bookMarks = FindBookmarks(doc.MainDocumentPart.Document);
    
    foreach( var end in bookMarks )
    {
        var textElement = new Text("asdfasdf");
        var runElement = new Run(textElement);
    
        end.Value.InsertAfterSelf(runElement);
    }
    

    From what I can tell inserting into and replacing the bookmarks looks harder. When I used InsertAt instead of InsertIntoSelf I got: "Non-composite elements do not have child elements." YMMV

提交回复
热议问题