如何通过保留格式使用 MS Word Web 加载项替换文本? [英] How to replace text with a MS Word web add-in by preserving the formatting?

查看:33
本文介绍了如何通过保留格式使用 MS Word Web 加载项替换文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a simple grammar correction web 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 the coercion type, I lose formatting. If there is a table or image in the selected text, they are also gone!

从我迄今为止所做的调查中了解到,openxml 是要走的路.但是我在网上找不到任何有用的例子.如何通过保留原始格式数据来操作文本?如何忽略非文本段落?我希望能够使用 Office JavaScript API 做到这一点:

As I understand from the investigation I've been doing so far, openxml is the way to go. But I couldn't find any useful example on the web. How can I manipulate text by preserving the original formatting data? How can I ignore non-text paragraphs? I want to be able to do this with the 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>/, '$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);
            }
        });
    }
});

这篇关于如何通过保留格式使用 MS Word Web 加载项替换文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆