How to replace text with MS Word web add-on while retaining formatting?

I am working on a simple web grammar add-in for MS Word. Basically, I want to get the selected text, make minimal changes and update the document with the corrected text. Currently, if I use β€œtext” as a type of coercion, I am losing formatting. If there is a table or image in the selected text, they also disappeared!

As I understand it from the research I have done so far, openxml is the way to go. But I could not find a single useful example on the Internet. How can I manipulate text while preserving the original formatting data? How to ignore non-text paragraphs? I want to be able to do this using the Office JavaScript API:

enter image description here

+4
source share
1 answer

I would do something like this:

// get data as OOXML
Office.context.document.getSelectedDataAsync(Office.CoercionType.Ooxml, function (result) {
    if (result.status === "succeeded") {
        var selectionAsOOXML = result.value;
        var bodyContentAsOOXML = selectionAsOOXML.match(/<w:body.*?>(.*?)<\/w:body>/)[1];

        // perform manipulations to the body
        // it can be difficult to do to OOXML but with som regexps it should be possible
        bodyContentAsOOXML = bodyContentAsOOXML.replace(/error/g, 'rorre'); // reverse the word 'error'

        // insert the body back in to the OOXML
        selectionAsOOXML = selectionAsOOXML.replace(/(<w:body.*?>)(.*?)<\/w:body>/, '$1' + bodyContentAsOOXML + '<\/w:body>');

        // replace the selected text with the new OOXML
        Office.context.document.setSelectedDataAsync(selectionAsOOXML, { coercionType: Office.CoercionType.Ooxml }, function (asyncResult) {
            if (asyncResult.status === "failed") {
                console.log("Action failed with error: " + asyncResult.error.message);
            }
        });
    }
});
+1
source

Source: https://habr.com/ru/post/1666198/


All Articles