我编写了以下函数来替换大量具有指定值的 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 秒。有没有更好/更快的方法来实现这一目标?
最佳答案
很好的跟进问题。我需要了解有关 replacementObject 数组有多大的更多详细信息,我假设至少与文档中内容控件的大小相同,这肯定会对您的方法的整体性能产生直接影响。如你所见from my previous answer ,用固定值更新 700 个 CC 不超过 5 秒,所以我认为你为找到新值所做的卫星操作对性能产生了负面影响。
具体来说,我看到您正在做的一些事情会对性能产生负面影响,您可能会修复。
- 您正在遍历至少 2 次内容控件集合。一个用于获取标题(并将它们插入临时数组),另一个用于替换内容(如果替换对象与文档中的 CC 匹配)。我真的会尝试一次性完成。
- 除此之外,在查找标题的内部循环中,您实际上遍历了每个 CC 的替换对象(这意味着您至少遍历了这个数组 700 次),更糟糕的是,您正在使用array.indexOf 键查找索引的方法(仅供引用,在我们用于加载项的浏览器中,最新的 IE,这是遍历数组的最昂贵的方式,实际上是 90%比你做一个 for 循环试图找到给定键的 indesx 慢,这个简单的改变理论上在最新的 IE 中会快 90%,如果你想保持这个逻辑)。 Check out this page demonstrating this (使用最新的IE浏览器进行测试)。
我认为您应该使用直接将其映射到 relacementObject 数组位置的索引来标记(或标题)每个内容控件(替换对象中的 title=index 并且直接使用 replacementObject 数组的索引来更改中的值一次通过。如果有办法做到这一点,您将获得最快的结果!
关于javascript - 通过 office-js 替换许多内容控件的文本的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45321706/