重要
本文适用于 常见 API,即 Office 2013 中引入的 Office JavaScript API 模型。 这些 API 包括在多种类型的 Office 应用程序中都很常见的 UI、对话框和客户端设置等功能。 Outlook 加载项仅使用通用 API,尤其是通过邮箱对象公开的 API 子集。
对于特定于应用程序的 API 不支持的场景,应仅使用通用 API。 若要了解何时使用通用 API(而非特定于应用程序的 API),请参阅了解 Office JavaScript API。
通过绑定,加载项可以一致地访问文档或电子表格的特定区域。 将绑定视为记住特定位置的书签,即使用户更改其选择或在文档中的其他位置导航也是如此。 具体而言,以下是绑定为加载项提供的功能。
- 跨支持的 Office 应用程序(如表、范围或文本)访问通用数据结构。
- 无需用户先进行选择即可读取和写入数据。
- 在加载项和文档数据之间创建持久关系。 绑定随文档一起保存,并跨会话工作。
若要创建绑定,请调用以下 Bindings 对象方法之一,以将文档区域与唯一标识符相关联: addFromPromptAsync、 addFromSelectionAsync 或 addFromNamedItemAsync。 建立绑定后,随时使用绑定标识符从该区域读取或写入该区域。
还可以订阅特定绑定区域的数据和选择更改事件。 这意味着外接程序仅收到有关绑定区域中的更改的通知,而不是整个文档。
选择正确的绑定类型
Office 支持 三种不同类型的绑定。 使用 addFromSelectionAsync、addFromPromptAsync 或 addFromNamedItemAsync 创建绑定时,可以使用 bindingType 参数指定类型。
文本绑定
文本绑定 - 绑定到可表示为文本的文档区域。
在Word,大多数连续选择都起作用。 在 Excel 中,只有单个单元格选择可以使用文本绑定。 Excel 仅支持纯文本,而 Word 支持三种格式:纯文本、HTML 和 Open XML for Office。
矩阵绑定
矩阵绑定 - 绑定到包含不带标头的表格数据的固定区域。
矩阵绑定中的数据在 JavaScript) 中以二维 数组 (数组的形式读取或写入。 例如,两列中的两行 字符串 值类似于 [['a', 'b'], ['c', 'd']],而包含三行的单个列为 [['a'], ['b'], ['c']]。
在 Excel 中,任何连续选择的单元格都适用于矩阵绑定。 在 Word 中,只有表格支持矩阵绑定。
表绑定
表绑定 - 绑定到包含具有标题的表的文档区域。
表绑定中的数据作为 TableData 对象进行读取或写入。 对象 TableData 通过 headers 和 rows 属性公开数据。
任何 Excel 或 Word 表格均可作为表格绑定的基础。 建立表绑定后,用户添加到表的新行或新列将自动包含在绑定中。
使用三个“addFrom”方法之一创建绑定后,可以使用相应的对象处理绑定的数据和属性: MatrixBinding、 TableBinding 或 TextBinding。 这三个对象都从 对象继承 getDataAsync 和 setDataAsync 方法, Binding 以便与绑定数据交互。
注意
应使用矩阵绑定还是表绑定?
处理包含总行的表格数据时,如果外接程序需要访问总行中的值,或者当用户选择总行时进行检测,请使用矩阵绑定。 表绑定不包括其 TableBinding.rowCount 属性或rowCount事件处理程序中 BindingSelectionChangedEventArgs 的 和 startRow 属性的总行数。 若要处理总行数,必须使用矩阵绑定。
从当前选定内容创建绑定
以下示例使用 addFromSelectionAsync 方法将名为 myBinding 的文本绑定添加到当前选定内容。
Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'myBinding' }, function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
write('Action failed. Error: ' + asyncResult.error.message);
} else {
write('Added new binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id);
}
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
在此示例中,绑定类型为文本,因此为所选内容创建 TextBinding 。 不同的绑定类型会公开不同的数据和操作。 Office.BindingType 是可用绑定类型的枚举。
第二个可选参数指定新绑定的 ID。 如果未指定 ID,则自动生成一个 ID。
作为最终 回调 参数传递的匿名函数在绑定创建完成后运行。 函数接收单个参数 , asyncResult该参数提供对具有调用状态的 AsyncResult 对象的访问。 属性 AsyncResult.value 包含对新创建的绑定的指定类型的 Binding 对象的引用。 可以使用此 Binding 对象来获取和设置数据。
从提示创建绑定
以下函数使用 addFromPromptAsync 方法添加名为 myBinding 的文本绑定。 此方法允许用户使用应用程序的内置范围选择提示指定绑定的范围。
function bindFromPrompt() {
Office.context.document.bindings.addFromPromptAsync(Office.BindingType.Text, { id: 'myBinding' }, function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
write('Action failed. Error: ' + asyncResult.error.message);
} else {
write('Added new binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
在此示例中,绑定类型为文本,因此会为提示中的用户选择创建 TextBinding 。
第二个参数包含新绑定的 ID。 如果未指定 ID,则自动生成一个 ID。
作为第三个 回调 参数传递的匿名函数在绑定创建完成后运行。 当回调函数运行时, AsyncResult 对象包含调用的状态和新创建的绑定。
以下屏幕截图显示了 Excel 中的内置范围选择提示。
向已命名项目添加绑定
以下函数使用 addFromNamedItemAsync 方法将绑定作为“矩阵”绑定添加到现有myRange命名项,并将绑定的 id 分配为“myMatrix”。
function bindNamedItem() {
Office.context.document.bindings.addFromNamedItemAsync("myRange", "matrix", {id:'myMatrix'}, function (result) {
if (result.status == 'succeeded'){
write('Added new binding with type: ' + result.value.type + ' and id: ' + result.value.id);
}
else
write('Error: ' + result.error.message);
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
对于Excel,addFromNamedItemAsyncitemName 的参数引用现有的命名区域、使用 A1 引用样式 () "A1:A3" 指定的区域或表。 默认情况下,Excel 为第一个表分配名称“Table1”,为第二个表分配名称“Table2”,依此而论。 若要在 Excel UI 中为表分配有意义的名称,请使用表工具 | 上的表名称属性“设计”选项卡。
注意
在 Excel 中,将表格指定为命名项目时,必须完全限定名称,以包含此格式的工作表名称 ("Sheet1!Table1" 例如) 。
以下函数在 Excel 中创建一个绑定到列 A ("A1:A3") 的前三个单元格,分配 ID "MyCities",然后将三个城市名称写入该绑定。
function bindingFromA1Range() {
Office.context.document.bindings.addFromNamedItemAsync("A1:A3", "matrix", { id: "MyCities" },
function (asyncResult) {
if (asyncResult.status == "failed") {
write('Error: ' + asyncResult.error.message);
} else {
// Write data to the new binding.
Office.select("bindings#MyCities").setDataAsync([['Berlin'], ['Munich'], ['Duisburg']], { coercionType: "matrix" },
function (asyncResult) {
if (asyncResult.status == "failed") {
write('Error: ' + asyncResult.error.message);
}
});
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
对于Word,addFromNamedItemAsyncitemName 的参数引用Title内容控件的 Rich Text 属性。 (不能绑定到内容控件以外的 Rich Text 内容控件。)
默认情况下,内容控件未 Title 分配任何值。 若要在Word UI 中分配有意义的名称,请在“开发工具”选项卡上的“控件”组中插入格式文本内容控件后,使用“控件”组中的“属性”命令显示“内容控件属性”对话框。 然后将内容控件的 属性设置为 Title 要从代码引用的名称。
以下函数在 Word 创建一个名为 的富文本内容控件"FirstName"的文本绑定,分配 ID"firstName",然后显示该信息。
function bindContentControl() {
Office.context.document.bindings.addFromNamedItemAsync('FirstName',
Office.BindingType.Text, {id:'firstName'},
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
write('Control bound. Binding.id: '
+ result.value.id + ' Binding.type: ' + result.value.type);
} else {
write('Error:', result.error.message);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
获取所有绑定
以下示例使用 getAllAsync 方法获取文档中的所有绑定。
Office.context.document.bindings.getAllAsync(function (asyncResult) {
let bindingString = '';
for (let i in asyncResult.value) {
bindingString += asyncResult.value[i].id + '\n';
}
write('Existing bindings: ' + bindingString);
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
作为参数传递的 callback 匿名函数在作完成时运行。 函数使用单个参数 调用, asyncResult该参数包含文档中绑定的数组。 通过循环访问该数组可以生成包含绑定 ID 的字符串。 然后,会在消息框中显示该字符串。
使用 getByIdAsync 按 ID 获取绑定
以下示例使用 getByIdAsync 方法通过指定绑定 ID 获取文档中的绑定。 此示例假定已使用本文前面所述的方法之一将名为 的 'myBinding' 绑定添加到文档中。
Office.context.document.bindings.getByIdAsync('myBinding', function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
write('Action failed. Error: ' + asyncResult.error.message);
}
else {
write('Retrieved binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id);
}
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
在此示例中,第一个 id 参数是要检索的绑定的 ID。
作为第二个 回调 参数传递的匿名函数在作完成时运行。 函数使用单个参数 asyncResult 调用,该参数包含调用的状态和 ID 为“myBinding”的绑定。
使用 按 ID 获取绑定 Office.select
以下示例使用 Office.select 函数通过在选择器字符串中指定绑定对象承诺的 ID 来获取文档中的 Binding 对象承诺。 然后,它调用 getDataAsync 方法以从指定的绑定获取数据。 此示例假定已使用本文前面所述的方法之一将名为 的 'myBinding' 绑定添加到文档中。
Office.select("bindings#myBinding", function onError(){}).getDataAsync(function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
write('Action failed. Error: ' + asyncResult.error.message);
} else {
write(asyncResult.value);
}
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
select如果函数 promise 成功返回 Binding 对象,该对象仅公开以下四种方法:getDataAsync、setDataAsync、addHandlerAsync 和 removeHandlerAsync。 如果 promise 无法返回 Binding 对象, onError 则回调可用于访问 asyncResult.error 对象以获取详细信息。 如果需要调用 Binding 对象的成员,而不是函数返回select的 Binding 对象承诺公开的四种方法,请改用 getByIdAsync 方法,方法是使用 Document.bindings 属性和 getByIdAsync 方法来检索 Binding 对象。
按 ID 释放绑定
以下示例使用 releaseByIdAsync 方法通过指定绑定 ID 在文档中发布绑定。
Office.context.document.bindings.releaseByIdAsync('myBinding', function (asyncResult) {
write('Released myBinding!');
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
在此示例中,第一个 id 参数是要发布的绑定的 ID。
作为第二个参数传递的匿名函数是在作完成时运行的回调。 使用包含调用状态的单个参数 asyncResult 调用函数。
从绑定中读取数据
以下示例使用 getDataAsync 方法从现有绑定获取数据。
myBinding.getDataAsync(function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
write('Action failed. Error: ' + asyncResult.error.message);
} else {
write(asyncResult.value);
}
});
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
myBinding 是包含文档中的现有文本绑定的变量。 或者,可以使用 Office.select 按绑定 ID 访问绑定,并启动 对 getDataAsync 方法的调用,如下所示:
Office.select("bindings#myBindingID").getDataAsync
传入方法的匿名函数是在作完成时运行的回调。
AsyncResult.value 属性包含 myBinding 中的数据。 值的类型取决于绑定类型。 此示例中的绑定是文本绑定,因此该值将包含字符串。 有关使用矩阵和表格绑定的其他示例,请参阅 getDataAsync 方法主题。
向绑定中写入数据
以下示例使用 setDataAsync 方法在现有绑定中设置数据。
myBinding.setDataAsync('Hello World!', function (asyncResult) { });
myBinding 是包含文档中的现有文本绑定的变量。
在此示例中,第一个参数是在 上 myBinding设置的值。 由于这是文本绑定,因此值为 string。 不同绑定类型接受不同类型的数据。
传入方法的匿名函数是在作完成时运行的回调。 函数使用包含结果状态的单个参数 asyncResult调用。
检测绑定中的数据或所选内容更改
以下函数将事件处理程序附加到 ID 为“MyBinding”的绑定的 DataChanged 事件。
function addHandler() {
Office.select("bindings#MyBinding").addHandlerAsync(
Office.EventType.BindingDataChanged, dataChanged);
}
function dataChanged(eventArgs) {
write('Bound data changed in binding: ' + eventArgs.binding.id);
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
myBinding 是包含文档中现有文本绑定的变量。
addHandlerAsync 的第一个 eventType 参数指定要订阅的事件的名称。
Office.EventType 是可用事件类型值的枚举。
Office.EventType.BindingDataChanged 计算结果为字符串“bindingDataChanged”。
dataChanged作为第二个处理程序参数传递的函数是在绑定中的数据发生更改时运行的事件处理程序。 该函数用单个参数 eventArgs 来调用,其中包含对绑定的引用。 此绑定可用来检索更新的数据。
类似地,你可以通过向绑定的 SelectionChanged 事件附加事件处理程序来检测用户是否更改绑定中的选择。 为此,请将 eventTypeaddHandlerAsync 的参数指定为 Office.EventType.BindingSelectionChanged 或 "bindingSelectionChanged"。
可以通过再次调用 addHandlerAsync 并传入参数的其他事件处理程序函数 handler ,为给定事件添加多个事件处理程序。 每个事件处理程序函数的名称必须唯一。
删除事件处理程序
若要删除事件的事件处理程序,请调用 removeHandlerAsync 作为第一个 eventType 参数传入事件类型,并调用要删除的事件处理程序函数的名称作为第二个 处理程序 参数。 例如,以下函数删除在 dataChanged 上一部分的示例中添加的事件处理程序函数。
function removeEventHandlerFromBinding() {
Office.select("bindings#MyBinding").removeHandlerAsync(
Office.EventType.BindingDataChanged, {handler:dataChanged});
}
重要
如果在调用 removeHandlerAsync 时省略了可选 handler 参数,则将删除指定 eventType 的所有事件处理程序。