如何通过保留格式用 MS Word Web 加载项替换文本?

How to replace text with a MS Word web add-in by preserving the formatting?

我正在为 MS Word 开发一个简单的语法更正 Web 插件。基本上,我想获取选定的文本,进行最少的更改并使用更正后的文本更新文档。目前,如果我使用 'text' 作为强制类型,我会丢失格式。如果所选文本中有 table 或图像,它们也消失了!

据我目前所做的调查了解,openxml 是可行的方法。但是我在网上找不到任何有用的例子。如何通过保留原始格式数据来操作文本?如何忽略非文本段落?我希望能够使用 Office JavaScript API:

我会这样做:

// 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>/, '' + 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);
            }
        });
    }
});