Office.Binding interface

Represents a binding to a section of the document.

The Binding object exposes the functionality possessed by all bindings regardless of type.

The Binding object is never called directly. It is the abstract parent class of the objects that represent each type of binding: Office.MatrixBinding, Office.TableBinding, or Office.TextBinding. All three of these objects inherit the getDataAsync and setDataAsync methods from the Binding object that enable to you interact with the data in the binding. They also inherit the ID and type properties for querying those property values. Additionally, the MatrixBinding and TableBinding objects expose additional methods for matrix- and table-specific features, such as counting the number of rows and columns.

Remarks

Applications: Word, Excel (deprecated, use Excel.Binding instead)

Requirement sets:

Properties

document

Get the Document object associated with the binding.

id

A string that uniquely identifies this binding among the bindings in the same Office.Document object.

type

Gets the type of the binding.

Methods

addHandlerAsync(eventType, handler, options, callback)

Adds an event handler to the object for the specified Office.EventType. Supported EventTypes are Office.EventType.BindingDataChanged and Office.EventType.BindingSelectionChanged.

addHandlerAsync(eventType, handler, callback)

Adds an event handler to the object for the specified Office.EventType. Supported EventTypes are Office.EventType.BindingDataChanged and Office.EventType.BindingSelectionChanged.

getDataAsync(options, callback)

Returns the data contained within the binding.

getDataAsync(callback)

Returns the data contained within the binding.

removeHandlerAsync(eventType, options, callback)

Removes the specified handler from the binding for the specified event type.

removeHandlerAsync(eventType, callback)

Removes the specified handler from the binding for the specified event type.

setDataAsync(data, options, callback)

Writes data to the bound section of the document represented by the specified binding object.

setDataAsync(data, callback)

Writes data to the bound section of the document represented by the specified binding object.

Property Details

document

Get the Document object associated with the binding.

document: Office.Document;

Property Value

Examples

Office.context.document.bindings.getByIdAsync("myBinding", function (asyncResult) {
    write(asyncResult.value.document.url);
});

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

id

A string that uniquely identifies this binding among the bindings in the same Office.Document object.

id: string;

Property Value

string

Examples

Office.context.document.bindings.getByIdAsync("myBinding", function (asyncResult) {
    write(asyncResult.value.id);
});

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

type

Gets the type of the binding.

type: Office.BindingType;

Property Value

Examples

Office.context.document.bindings.getByIdAsync("MyBinding", function (asyncResult) { 
    write(asyncResult.value.type); 
}) 

// Function that writes to a div with id='message' on the page. 
function write(message){ 
    document.getElementById('message').innerText += message;  
}

Method Details

addHandlerAsync(eventType, handler, options, callback)

Adds an event handler to the object for the specified Office.EventType. Supported EventTypes are Office.EventType.BindingDataChanged and Office.EventType.BindingSelectionChanged.

addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For bindings, it can be Office.EventType.BindingDataChanged or Office.EventType.BindingSelectionChanged.

handler

any

The event handler function to add, whose only parameter is of type Office.BindingDataChangedEventArgs or Office.BindingSelectionChangedEventArgs.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: BindingEvents

You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique.

addHandlerAsync(eventType, handler, callback)

Adds an event handler to the object for the specified Office.EventType. Supported EventTypes are Office.EventType.BindingDataChanged and Office.EventType.BindingSelectionChanged.

addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For bindings, it can be Office.EventType.BindingDataChanged or Office.EventType.BindingSelectionChanged.

handler

any

The event handler function to add, whose only parameter is of type Office.BindingDataChangedEventArgs or Office.BindingSelectionChangedEventArgs.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: BindingEvents

You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique.

Examples

// The following code sample calls the select function of the Office object to access the binding
// with ID "MyBinding", and then calls the addHandlerAsync method to add a handler function 
// for the bindingDataChanged event of that binding.
function addEventHandlerToBinding() {
    Office.select("bindings#MyBinding").addHandlerAsync(
        Office.EventType.BindingDataChanged, onBindingDataChanged);
}

function onBindingDataChanged(eventArgs) {
    write("Data has 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; 
}
// To add an event handler for the BindingSelectionChanged event of a binding, 
// use the addHandlerAsync method of the Binding object.
// The event handler receives an argument of type BindingSelectionChangedEventArgs.
function addEventHandlerToBinding() {
    Office.select("bindings#MyBinding").addHandlerAsync(
        Office.EventType.BindingSelectionChanged, onBindingSelectionChanged);
}

function onBindingSelectionChanged(eventArgs) {
    write(eventArgs.binding.id + " has been selected.");
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

getDataAsync(options, callback)

Returns the data contained within the binding.

getDataAsync<T>(options?: GetBindingDataOptions, callback?: (result: AsyncResult<T>) => void): void;

Parameters

options
Office.GetBindingDataOptions

Provides options for how to get the data in a binding.

callback

(result: Office.AsyncResult<T>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the values in the specified binding. If the coercionType parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic.

Returns

void

Remarks

Requirement sets:

When called from a MatrixBinding or TableBinding, the getDataAsync method will return a subset of the bound values if the optional startRow, startColumn, rowCount, and columnCount parameters are specified (and they specify a contiguous and valid range).

getDataAsync(callback)

Returns the data contained within the binding.

getDataAsync<T>(callback?: (result: AsyncResult<T>) => void): void;

Parameters

callback

(result: Office.AsyncResult<T>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the values in the specified binding. If the coercionType parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic.

Returns

void

Remarks

Requirement sets:

When called from a MatrixBinding or TableBinding, the getDataAsync method will return a subset of the bound values if the optional startRow, startColumn, rowCount, and columnCount parameters are specified (and they specify a contiguous and valid range).

Examples

function showBindingData() {
    Office.select("bindings#MyBinding").getDataAsync(function (asyncResult) {
        write(asyncResult.value)
    });
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

// There is an important difference in behavior between using the "table" and "matrix" coercionType with the
// Binding.getDataAsync method, with respect to data formatted with header rows, as shown in the following
// two examples. These code examples show event handler functions for the Binding.SelectionChanged event.

// If you specify the "table" coercionType, the TableData.rows property ( result.value.rows in the following
// code example) returns an array that contains only the body rows of the table. So, its 0th row will be the
// first non-header row in the table.
function selectionChanged(evtArgs) { 
    Office.select("bindings#TableTranslate").getDataAsync(
        { coercionType: 'table', 
          startRow: evtArgs.startRow, 
          startCol: 0, 
          rowCount: 1, 
          columnCount: 1 },  
        function (result) { 
            if (result.status == 'succeeded') { 
                write("Image to find: " + result.value.rows[0][0]); 
            } 
            else 
                write(result.error.message); 
    }); 
}     
// Function that writes to a div with id='message' on the page. 
function write(message){ 
    document.getElementById('message').innerText += message; 
}

// However, if you specify the "matrix" coercionType, result.value in the following code example returns an array
// that contains the table header in the 0th row. If the table header contains multiple rows, then these are all
// included in the result.value matrix as separate rows before the table body rows are included.
function selectionChanged(evtArgs) { 
    Office.select("bindings#TableTranslate").getDataAsync(
        { coercionType: 'matrix', 
          startRow: evtArgs.startRow, 
          startCol: 0, 
          rowCount: 1, 
          columnCount: 1 },  
        function (result) { 
            if (result.status == 'succeeded') { 
                write("Image to find: " + result.value[1][0]); 
            } 
            else 
                write(result.error.message); 
    }); 
}     
// Function that writes to a div with id='message' on the page. 
function write(message){ 
    document.getElementById('message').innerText += message; 
}

removeHandlerAsync(eventType, options, callback)

Removes the specified handler from the binding for the specified event type.

removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For bindings, it can be Office.EventType.BindingDataChanged or Office.EventType.BindingSelectionChanged.

options
Office.RemoveHandlerOptions

Provides options to determine which event handler or handlers are removed.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: BindingEvents

removeHandlerAsync(eventType, callback)

Removes the specified handler from the binding for the specified event type.

removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For bindings, it can be Office.EventType.BindingDataChanged or Office.EventType.BindingSelectionChanged.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: BindingEvents

Examples

function removeEventHandlerFromBinding() {
    Office.select("bindings#MyBinding").removeHandlerAsync(
        Office.EventType.BindingDataChanged, {handler:onBindingDataChanged});
}

setDataAsync(data, options, callback)

Writes data to the bound section of the document represented by the specified binding object.

setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

data

Office.TableData | any

The data to be set in the current selection. Possible data types by Office application:

string: Excel on the web and Windows, and Word on the web and Windows only

array of arrays: Excel and Word only

Office.TableData: Excel and Word only

HTML: Word on the web and Windows only

Office Open XML: Word only

options
Office.SetBindingDataOptions

Provides options for how to set the data in a binding.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement sets:

The value passed for data contains the data to be written in the binding. The kind of value passed determines what will be written as described in the following table.

data value Data written
A string Plain text or anything that can be coerced to a string will be written.
An array of arrays ("matrix") Tabular data without headers will be written. For example, to write data to three rows in two columns, you can pass an array like this: \[\["R1C1", "R1C2"\], \["R2C1", "R2C2"\], \["R3C1", "R3C2"\]\]. To write a single column of three rows, pass an array like this: \[\["R1C1"\], \["R2C1"\], \["R3C1"\]\].
A TableData object A table with headers will be written.

Additionally, these application-specific actions apply when writing data to a binding. For Word, the specified data is written to the binding as follows.

data value Data written
A string The specified text is written.
An array of arrays ("matrix") or a TableData object A Word table is written.
HTML The specified HTML is written. If any of the HTML you write is invalid, Word will not raise an error. Word will write as much of the HTML as it can and will omit any invalid data.
Office Open XML ("Open XML") The specified the XML is written.

For Excel, the specified data is written to the binding as follows.

data value Data written
A string The specified text is inserted as the value of the first bound cell. You can also specify a valid formula to add that formula to the bound cell. For example, setting data to "=SUM(A1:A5)" will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Binding.getDataAsync method on the bound cell to read its data, the method can return only the data displayed in the cell (the formula's result).
An array of arrays ("matrix"), and the shape exactly matches the shape of the binding specified The set of rows and columns are written.You can also specify an array of arrays that contain valid formulas to add them to the bound cells. For example, setting data to \[\["=SUM(A1:A5)","=AVERAGE(A1:A5)"\]\] will add those two formulas to a binding that contains two cells. Just as when setting a formula on a single bound cell, you can't read the added formulas (or any pre-existing formulas) from the binding with the Binding.getDataAsync method - it returns only the data displayed in the bound cells.
A TableData object, and the shape of the table matches the bound table The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".

For Excel on the web:

  • The total number of cells in the value passed to the data parameter can't exceed 20,000 in a single call to this method.

  • The number of formatting groups passed to the cellFormat parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.

In all other cases, an error is returned.

The setDataAsync method will write data in a subset of a table or matrix binding if the optional startRow and startColumn parameters are specified, and they specify a valid range.

In the callback function passed to the setDataAsync method, you can use the properties of the AsyncResult object to return the following information.

Property Use
AsyncResult.value Always returns undefined because there is no object or data to retrieve
AsyncResult.status Determine the success or failure of the operation
AsyncResult.error Access an Error object that provides error information if the operation failed
AsyncResult.asyncContext Define an item of any type that is returned in the AsyncResult object without being altered

setDataAsync(data, callback)

Writes data to the bound section of the document represented by the specified binding object.

setDataAsync(data: TableData | any, callback?: (result: AsyncResult<void>) => void): void;

Parameters

data

Office.TableData | any

The data to be set in the current selection. Possible data types by Office application:

string: Excel on the web and Windows, and Word on the web and Windows only

array of arrays: Excel and Word only

TableData: Excel and Word only

HTML: Word on the web and Windows only

Office Open XML: Word only

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement sets:

The value passed for data contains the data to be written in the binding. The kind of value passed determines what will be written as described in the following table.

data value Data written
A string Plain text or anything that can be coerced to a string will be written.
An array of arrays ("matrix") Tabular data without headers will be written. For example, to write data to three rows in two columns, you can pass an array like this: \[\["R1C1", "R1C2"\], \["R2C1", "R2C2"\], \["R3C1", "R3C2"\]\]. To write a single column of three rows, pass an array like this: \[\["R1C1"\], \["R2C1"\], \["R3C1"\]\].
A TableData object A table with headers will be written.

Additionally, these application-specific actions apply when writing data to a binding. For Word, the specified data is written to the binding as follows.

data value Data written
A string The specified text is written.
An array of arrays ("matrix") or a TableData object A Word table is written.
HTML The specified HTML is written. If any of the HTML you write is invalid, Word will not raise an error. Word will write as much of the HTML as it can and will omit any invalid data.
Office Open XML ("Open XML") The specified the XML is written.

For Excel, the specified data is written to the binding as follows.

data value Data written
A string The specified text is inserted as the value of the first bound cell. You can also specify a valid formula to add that formula to the bound cell. For example, setting data to "=SUM(A1:A5)" will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Binding.getDataAsync method on the bound cell to read its data, the method can return only the data displayed in the cell (the formula's result).
An array of arrays ("matrix"), and the shape exactly matches the shape of the binding specified The set of rows and columns are written.You can also specify an array of arrays that contain valid formulas to add them to the bound cells. For example, setting data to \[\["=SUM(A1:A5)","=AVERAGE(A1:A5)"\]\] will add those two formulas to a binding that contains two cells. Just as when setting a formula on a single bound cell, you can't read the added formulas (or any pre-existing formulas) from the binding with the Binding.getDataAsync method - it returns only the data displayed in the bound cells.
A TableData object, and the shape of the table matches the bound table The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".

For Excel on the web:

  • The total number of cells in the value passed to the data parameter can't exceed 20,000 in a single call to this method.

  • The number of formatting groups passed to the cellFormat parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.

In all other cases, an error is returned.

The setDataAsync method will write data in a subset of a table or matrix binding if the optional startRow and startColumn parameters are specified, and they specify a valid range.

In the callback function passed to the setDataAsync method, you can use the properties of the AsyncResult object to return the following information.

Property Use
AsyncResult.value Always returns undefined because there is no object or data to retrieve
AsyncResult.status Determine the success or failure of the operation
AsyncResult.error Access an Error object that provides error information if the operation failed
AsyncResult.asyncContext Define an item of any type that is returned in the AsyncResult object without being altered

Examples

function setBindingData() {
    Office.select("bindings#MyBinding").setDataAsync('Hello World!', function (asyncResult) { });
}

// Specifying the optional coercionType parameter lets you specify the kind of data you want to write to a binding.
// For example, in Word if you want to write HTML to a text binding, you can specify the coercionType parameter 
// as "html" as shown in the following example, which uses HTML <b> tags to make "Hello" bold.
function writeHtmlData() {
    Office.select("bindings#myBinding").setDataAsync(
        "<b>Hello</b> World!", {coercionType: "html"}, 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; 
}

// In this example, the call to setDataAsync passes the data parameter as an array of arrays
// (to create a single column of three rows), and specifies the data structure with the 
// coercionType parameter as a "matrix".
function writeBoundDataMatrix() {
    Office.select("bindings#myBinding").setDataAsync(
        [['Berlin'],['Munich'],['Duisburg']],{ coercionType: "matrix" }, function (asyncResult) {
        if (asyncResult.status == "failed") {
            write('Error: ' + asyncResult.error.message);
        } else {
            write('Bound data: ' + asyncResult.value);
        }
    });
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

// In the writeBoundDataTable function in this example, the call to setDataAsync passes the data parameter 
// as a TableData object (to write three columns and three rows), and specifies the data structure
// with the coercionType parameter as a "table".

// In the updateTableData function, the call to setDataAsync again passes the data parameter as a TableData object,
// but as a single column with a new header and three rows, to update the values in the last column 
// of the table created with the writeBoundDataTable function. The optional zero-based startColumn parameter 
// is specified as 2 to replace the values in the third column of the table.
function writeBoundDataTable() {
    // Create a TableData object.
    const myTable = new Office.TableData();
    myTable.headers = ['First Name', 'Last Name', 'Grade'];
    myTable.rows = [['Kim', 'Abercrombie', 'A'], ['Junmin','Hao', 'C'],['Toni','Poe','B']];

    // Set myTable in the binding.
    Office.select("bindings#myBinding").setDataAsync(myTable, { coercionType: "table" }, 
        function (asyncResult) {
            if (asyncResult.status == Office.AsyncResultStatus.Failed) {
                write('Error: '+ asyncResult.error.message);
        } else {
            write('Bound data: ' + asyncResult.value);
        }
    });
}

// Replace last column with different data.
function updateTableData() {
    const newTable = new Office.TableData();
    newTable.headers = ["Gender"];
    newTable.rows = [["M"],["M"],["F"]];
    Office.select("bindings#myBinding").setDataAsync(newTable, { coercionType: "table", startColumn:2 }, 
        function (asyncResult) {
            if (asyncResult.status == Office.AsyncResultStatus.Failed) {
                write('Error: '+ asyncResult.error.message);
        } else {
            write('Bound data: ' + asyncResult.value);
        }     
    });   
}

// In this example, the following call passes two formatting groups to cellFormat.
Office.select("bindings#myBinding").setDataAsync([['Berlin'],['Munich'],['Duisburg']],
  {cellFormat:[{cells: {row: 1}, format: {fontColor: "yellow"}}, 
      {cells: {row: 3, column: 4}, format: {borderColor: "white", fontStyle: "bold"}}]}, 
  function (asyncResult){});