通过office-js替换许多内容控件的文本的最快方法是什么?

时间:2017-07-26 08:41:46

标签: javascript ms-word ms-office office-js office-addins

我编写了以下函数来替换大量具有指定值的CC:

/** replaceManyCCs()
 *
 * Replaces the content of many content controls, based on the replacementObject.
 *
 * @arg replacementObject   A dictionary. The keys are the titles of the CCs which should be replaced. The values are the replacement values.
 */
function replaceManyCCs (replacementObject) {
    Word.run(function (context) {
        var time1 = Date.now();

        // load the title of all content controls
        var CCc = context.document.contentControls.load('title');

        return context.sync().then(function () { // synchronous
            // extract CC titles
            var documentCCtitleList = [];
            for(var i = 0; i < CCc.items.length; i++) { documentCCtitleList.push(CCc.items[i].title); }

            // check for missing titles and replace
            var replaceCounter = 0;
            for(var key in replacementObject) {
                var index = documentCCtitleList.indexOf(key);
                if(index == -1) { // title is missing
                    throw 'Could not find CC with title "'+key+'"';
                }
                else { // replace
                    CCc.items[index].insertText(' '+replacementObject[key], 'Replace');
                    replaceCounter++;
                }
            }

            $('#status').html('...replacing...');

            return context.sync().then(function () {
                var time2 = Date.now();
                var tdiff = time2-time1;
                $('#status').html('Replaced '+replaceCounter+' CCs in '+(tdiff/1000)+' seconds');
            });
        });
    }).catch(function (error) {
        $('#status').html('<pre>Error: ' + JSON.stringify(error, null, 4) + '</pre>');
        console.log('Error: ' + JSON.stringify(error, null, 4));
        if (error instanceof OfficeExtension.Error) {
            console.log('Debug info: ' + JSON.stringify(error.debugInfo, null, 4));
        }
    });
}

使用此代码替换816 CC需要50-60秒。有没有更好/更快的方法来实现这个目标?

1 个答案:

答案 0 :(得分:1)

良好的跟进问题。我需要知道有关replacementObject数组有多大的更多细节我假设至少与文档中的内容控件的大小相同,这肯定会直接影响方法的整体性能。正如您所看到的from my previous answer,使用固定值更新700个CC不会超过5秒,因此我认为您正在进行的查找新值的卫星操作会对性能产生负面影响。

具体来说,我看到你正在做的一些事情对性能产生负面影响,你可能会有所修复。

  1. 您正在遍历内容控件集合的至少2倍。一个用于获取标题(并将它们推入临时数组),另一个用于替换内容(如果替换对象与文档中的CC匹配)。我真的会尝试一次性完成这件事。
  2. 除此之外,在你正在寻找标题的内部循环中,你实际上遍历每个CC的replacementObject(这意味着至少你正在遍历这个数组700次)并且使你正在使用的事情变得更糟通过键查找索引的array.indexOf方法(我们用于加载项的浏览器中的FYI,最新的IE,这是遍历数组的最昂贵的方式,实际上是90%如果你做一个for循环试图找到给定键的indesx,那么这个简单的改变在理论上会比最新的IE快90%,如果你想保持这个逻辑)。 Check out this page demonstrating this(使用最新的IE浏览器进行测试)。 enter image description here
  3. 我认为你应该使用索引标记(或标题)每个内容控件,该索引直接将其映射到relacementObject数组位置(标题=替换对象中的索引,只需直接使用replacementObject数组的索引来更改一次通过。如果有办法,你将获得最快的结果!