如何使用MS Word Web插件替换文本并保留格式?

4
我正在为MS Word开发一个简单的语法纠错Web插件。基本上,我想获取所选文本,进行最小的更改并使用更正后的文本更新文档。目前,如果我使用“文本”作为强制类型,我会失去格式。如果所选文本中有表格或图像,它们也会消失!
据我目前的调查所了解,openxml是正确的方法。但我在网上找不到任何有用的示例。如何通过保留原始格式数据来操纵文本?如何忽略非文本段落?我希望能够在Office JavaScript API中实现这一点:

enter image description here

1个回答

1
我会做这样的事情:
// 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);
            }
        });
    }
});

关于我的回答,你有任何问题吗? - jkh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接