1
使用Office的JavaScript API,我嘗試使用下面的代碼填寫所選表:的MS Word API:設置表中的值加載異步
Word.run(function (context) {
var table = context.document.getSelection().parentTable;
table.load("values, rows/items/cells/items/body");
context.trackedObjects.add(table);
return context.sync().then(function() {
// loop over table
for (var row = 0; row < table.values.length; row++) {
for (var column = 0; column < table.values[row].length; column++) {
// use closures to keep cell index variables for ajax
(function (row, column, table, context) {
if ((table.values[row][column].trim() ==
"" || !table.values[row][column]) &&
table.values[row][0] && table.values[0][column]) {
$.ajax({
url: "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" +
table.values[row][0].replace(/\s/g, '') +
"/property/" + table.values[0][column] + "/txt"
}).done(function (data) {
// insert data
table.rows.items[row].cells.items[column].body.insertText(data);
console.log("data: " + data);
return context.sync().then(function() {
console.log("synced");
}).catch(function (e) {
console.log("0");
errorHandler(e);
});
}).error(function (e) {
console.log("1");
errorHandler(e);
});
} else {
console.log(row + " " + column + " not beeing set, it is " +
table.values[row][column]);
}
})(row, column, table, context);
}
}
}).then(context.sync().then(
function() {
console.log("last sync?");
}
).catch(function (e) {
console.log("2");
errorHandler(e);
}));
}).catch(function (e) {
console.log("3");
errorHandler(e);
});
但不知何故,這不起作用作爲拋出異常:
ItemNotFound: ItemNotFound
錯誤的來源是 - 根據日誌(0
),並在該插入數據部分的錯誤("errorLocation":"TableRowCollection.getItem"
)。
如何告訴Word讓我將表變量保留一段時間,因爲一旦我的Ajax完成,我將更新其內容?