首页 文章

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

提问于
浏览
4

我正在为MS Word编写一个简单的语法修正Web插件 . 基本上,我想获取所选文本,进行最小化更改并使用更正后的文本更新文档 . 目前,如果我使用'text'作为强制类型,我将失去格式 . 如果所选文本中有表格或图像,它们也会消失!

据我所知,到目前为止我一直在做的调查,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);
                }
            });
        }
    });
    

相关问题