1
我開發了Office加載項,對處理JSON格式數據的Word文檔的每個段落的文字和index.html文件中的結果寫入該在任務窗格中呈現。這工作正常。我現在試圖格式化Word文檔中對應於JSON數據中鍵值的字符串。在辦公室使用Word.SearchOptions外接
我在index.html文件我稱之爲「Office.initialize」和定義基於JSON數據的變量的頭部的JS塊,並具有與上述功能的效用函數。之後,我得到Word上下文,並根據JSON數據處理Word文件段落,然後嘗試搜索Word段落以對格式進行格式化。在這最後一個任務中,我試圖重現Michael Mainer 1的片段。但是當我激活這個功能時沒有格式化。不幸的是我沒有訪問控制檯,因爲我在Mac上,這使得它更難調試。
我會很感激別人給我看,我要去哪裏錯了。
'功能測試儀(){ Word.run(函數(上下文){
// Create a proxy object for the document's paragraphs
var paragraphs = context.document.body.paragraphs;
// Load the paragraphs' text, which I run regexes on
context.load(paragraphs, 'text');
return context.sync().then(function() {
for (var i = 0; i < paragraphs.items.length; i++) {
var text = paragraphs.items[i].text;
// jquery to iterate over the "notes" objects from the JSON
$.each(notes, function(key, value) {
var regex = new RegExp("\\b" + key + "\\b", "g");
var res = regex.test(text);
// if the regex hits...
if (res == true) {
// This part works fine, using the JSON data to append to the <DIV> with ID = "notes"
document.getElementById('notes').innerHTML += "<button onclick=hide('" + value.seqNo + "')><b>" + key + "</b></button><p class='" + value.seqNo + "' id='" + i + "'>" + value.notes[0].note + "</p>";
// I now go on to searching for these hits within the current paragraph in the Word file
var thisPara = paragraphs.items[i];
// Set up the search options.
var options = Word.SearchOptions.newObject(context);
options.matchCase = false
// Queue the commmand to search the current paragraph for occurrences of the string "key" (coming from the JSON data)
var searchResults = paragraphs.items[i].search(key, options);
// Load 'text' and 'font' for searchResults.
context.load(searchResults, 'text, font');
// Synchronize the document state by executing the queued-up commands, and return a promise to indicate task completion.
return context.sync().then(function() {
// Queue a command to change the font for each found item.
for (var j = 0; j < searchResults.items.length; j++) {
searchResults.items[j].font.color = '#FF0000'
searchResults.items[j].font.highlightColor = '#FFFF00';
searchResults.items[j].font.bold = true;
}
// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync();
});
}
});
}
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
} `
我這樣做了(請參閱代碼中的「context.load(searchResults,'text,font');」)。我認爲問題來自於想要搜索一系列術語,而不僅僅是像Michael Mainer's那樣的例子。當我創建一個單獨的JS函數來循環訪問這個數組,並將它們逐個發送給在Word中搜索的函數時,它就結束了工作。 – tioken