Replace bookmark text in Word file using Open XML SDK

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

    I took the code from the answer, and had several problems with it for exceptional cases:

    1. You might want to ignore hidden bookmarks. Bookmarks are hidden if the name starts with an _ (underscore)
    2. If the bookmark is for one more more TableCell's, you will find it in the BookmarkStart in the first Cell of the row with the property ColumnFirst refering to the 0-based column index of the cell where the bookmark starts. ColumnLast refers to the cell where the bookmark ends, for my special case it was always ColumnFirst == ColumnLast (bookmarks marked only one column). In this case you also won't find a BookmarkEnd.
    3. Bookmarks can be empty, so a BookmarkStart follows directly a BookmarkEnd, in this case you can just call bookmarkStart.Parent.InsertAfter(new Run(new Text("Hello World")), bookmarkStart)
    4. Also a bookmark can contain many Text-elements, so you might want to Remove all the other elements, otherwise parts of the Bookmark might be replaced, while other following parts will stay.
    5. And I'm not sure if my last hack is necessary, since I don't know all the limitations of OpenXML, but after discovering the previous 4, I also didn't trust anymore that there will be a sibling of Run, with a child of Text. So instead I just look at all my siblings (until BookmarEnd which has the same ID as BookmarkStart) and check all the children until I find any Text. - Maybe somebody with more experience with OpenXML can answer if it is necessary?

    You can view my specific implementation here)

    Hope this helps some of you who experienced the same issues.

提交回复
热议问题