我编写了以下函数来替换大量具有指定值的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秒。有没有更好/更快的方法来实现这个目标?
答案 0 :(得分:1)
良好的跟进问题。我需要知道有关replacementObject数组有多大的更多细节我假设至少与文档中的内容控件的大小相同,这肯定会直接影响方法的整体性能。正如您所看到的from my previous answer,使用固定值更新700个CC不会超过5秒,因此我认为您正在进行的查找新值的卫星操作会对性能产生负面影响。
具体来说,我看到你正在做的一些事情对性能产生负面影响,你可能会有所修复。
我认为你应该使用索引标记(或标题)每个内容控件,该索引直接将其映射到relacementObject数组位置(标题=替换对象中的索引,只需直接使用replacementObject数组的索引来更改一次通过。如果有办法,你将获得最快的结果!