简体   繁体   中英

How to replace text at bookmark in a Word document

I am trying to programmatically replace text at a bookmark in a Word document. I can find the text at the bookmark (I am using a test document with only one bookmark), and print it out to debug - but can't seem to set the value of the text. How do I replace the text at the bookmark?

WordprocessingDocument wordprocessingDocument=WordprocessingDocument.Open(filepath, true);

foreach (BookmarkStart bookmark in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>())
{
    System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.Parent.InnerText);
    /* Below line does not work */
    bookmark.Parent.InnerText = "My Replacement Text"
}

Get all bookmark start

public List<WP.BookmarkStart> GetAllBookmarks ()
{
    var bmk = _workspace.MainDocumentPart.RootElement.Descendants<WP.BookmarkStart>().ToList();
    return bmk;
}

Iterate through all bookmarks

foreach (var bookmark in bookmarks)
{
    string modifiedString = GetModifiedString();
    ReplaceBookmarkText(bookmark, modifiedString);
}

Replace Bookmark Text

public void ReplaceBookmarkText(WP.BookmarkStart bookmark, string newText)
{
    try
    {
        var bmkText = bookmark.NextSibling<WP.Run>();
        if (bmkText != null)
        {
            bmkText.GetFirstChild<WP.Text>().Text = newText;
            wordprocessingDocument.MainDocumentPart.Document.Save();
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine(ex.Message);
        throw;
    }            
}

Where WP is

using WP = DocumentFormat.OpenXml.Wordprocessing;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM