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

╄→尐↘猪︶ㄣ 提交于 2021-02-07 19:13:48

问题


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!

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:


回答1:


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);
            }
        });
    }
});


来源:https://stackoverflow.com/questions/41539946/how-to-replace-text-with-a-ms-word-web-add-in-by-preserving-the-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!