Office.Document interface

An abstract class that represents the document the add-in is interacting with.

Remarks

HostsAccess, Excel, PowerPoint, Project, Word

Properties

bindings

Gets an object that provides access to the bindings defined in the document.

customXmlParts

Gets an object that represents the custom XML parts in the document.

mode

Gets the mode the document is in.

settings

Gets an object that represents the saved custom settings of the content or task pane add-in for the current document.

url

Gets the URL of the document that the host application currently has open. Returns null if the URL is unavailable.

Methods

addHandlerAsync(eventType, handler, options, callback)

Adds an event handler for a Document object event.

getActiveViewAsync(options, callback)

Returns the state of the current view of the presentation (edit or read).

getFileAsync(fileType, options, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFilePropertiesAsync(options, callback)

Gets file properties of the current document.

getMaxResourceIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project 2016 on Windows desktop.

getMaxTaskIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project 2016 on Windows desktop.

getProjectFieldAsync(fieldId, options, callback)

Project documents only. Get Project field (Ex. ProjectWebAccessURL).

getResourceByIndexAsync(resourceIndex, options, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project 2016 on Windows desktop.

getResourceFieldAsync(resourceId, fieldId, options, callback)

Project documents only. Get resource field for provided resource Id. (Ex.ResourceName)

getSelectedDataAsync(coerciontype, options, callback)

Reads the data contained in the current selection in the document.

getSelectedResourceAsync(options, callback)

Project documents only. Get the current selected Resource's Id.

getSelectedTaskAsync(options, callback)

Project documents only. Get the current selected Task's Id.

getSelectedViewAsync(options, callback)

Project documents only. Get the current selected View Type (Ex. Gantt) and View Name.

getTaskAsync(taskId, options, callback)

Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId.

getTaskByIndexAsync(taskIndex, options, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project 2016 on Windows desktop.

getTaskFieldAsync(taskId, fieldId, options, callback)

Project documents only. Get task field for provided task Id. (Ex. StartDate).

getWSSUrlAsync(options, callback)

Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too.

goToByIdAsync(id, goToType, options, callback)

Goes to the specified object or location in the document.

removeHandlerAsync(eventType, options, callback)

Removes an event handler for the specified event type.

setResourceFieldAsync(resourceId, fieldId, fieldValue, options, callback)

Project documents only. Set resource field for specified resource Id.

Important: This API works only in Project 2016 on Windows desktop.

setSelectedDataAsync(data, options, callback)

Writes the specified data into the current selection.

setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)

Project documents only. Set task field for specified task Id.

Important: This API works only in Project 2016 on Windows desktop.

Property Details

bindings

Gets an object that provides access to the bindings defined in the document.

bindings: Bindings;
Property Value
Remarks

You don't instantiate the Document object directly in your script. To call members of the Document object to interact with the current document or worksheet, use Office.context.document in your script.

Support details

A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
PowerPoint Y Y Y
Word Y Y Y

Examples

function displayAllBindings() {
    Office.context.document.bindings.getAllAsync(function (asyncResult) {
        var bindingString = '';
        for (var 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; 
}

customXmlParts

Gets an object that represents the custom XML parts in the document.

customXmlParts: CustomXmlParts;
Property Value
Remarks

Support details

A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y

Examples

function getCustomXmlParts(){
    Office.context.document.customXmlParts.getByNamespaceAsync('http://tempuri.org', function (asyncResult) {
        write('Retrieved ' + asyncResult.value.length + ' custom XML parts');
    });
}

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

mode

Gets the mode the document is in.

mode: DocumentMode;
Property Value
Remarks

Support details

A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y

Examples

function displayDocumentMode() {
    write(Office.context.document.mode);
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following example initializes the add-in and then gets properties of the
// Document object that are available in the context of a Project document.
// A Project document is the opened, active project. To access members of the
// ProjectDocument object, use the Office.context.document object as shown in
// the code examples for ProjectDocument methods and events.
// The example assumes your add-in has a reference to the jQuery library and
// that the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Get information about the document.
            showDocumentProperties();
        });
    };

    // Get the document mode and the URL of the active project.
    function showDocumentProperties() {
        var output = String.format(
            'The document mode is {0}.<br/>The URL of the active project is {1}.',
            Office.context.document.mode,
            Office.context.document.url);
        $('#message').html(output);
    }
})();

settings

Gets an object that represents the saved custom settings of the content or task pane add-in for the current document.

settings: Settings;
Property Value
Remarks

Support details

A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y

url

Gets the URL of the document that the host application currently has open. Returns null if the URL is unavailable.

url: string;
Property Value
string
Remarks

Support details

A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y
Word Y Y Y

Examples

function displayDocumentUrl() {
    write(Office.context.document.url);
}

// 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 for a Document object event.

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

For a Document object event, the eventType parameter can be specified as Office.EventType.Document.SelectionChanged or Office.EventType.Document.ActiveViewChanged, or the corresponding text value of this enumeration.

handler
any

The event handler function to add, whose only parameter is of type Office.DocumentSelectionChangedEventArgs. Required.

options
Office.AsyncContextOptions

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

callback
(result: 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 SetsDocumentEvents

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

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y

Examples

// The following example adds an event handler for the SelectionChanged event of a document
function addSelectionChangedEventHandler() {
    Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, MyHandler);
}

function MyHandler(eventArgs) {
    write('Event raised: ' + eventArgs.type);
    doSomethingWithDocument(eventArgs.document);
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following code example adds a handler for the ResourceSelectionChanged event.
// When the resource selection changes in the document, it gets the GUID of the selected resource.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ResourceSelectionChanged,
                getResourceGuid);
        });
    };

    // Get the GUID of the selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html(result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For a complete code sample that shows how to use a ResourceSelectionChanged
// event handler in a Project add-in, see "Create your first task pane add-in
// for Project 2013 by using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example adds a handler for the TaskSelectionChanged event.
// When the task selection changes in the document, it gets the GUID of the
// selected task.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.TaskSelectionChanged,
                getTaskGuid);
            getTaskGuid();
        });
    };

    // Get the GUID of the selected task and display it in the add-in.
    function getTaskGuid() {
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html(result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();
// The following code example adds a handler for the ViewSelectionChanged
// event. When the active view changes, it gets the name and type of the active view.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            getActiveView();
        });
    };

    // Get the name and type of the active view and display it in the add-in.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, result.value.viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For an example that shows how to use a ViewSelectionChanged event handler in a
// Project add-in, see "Create your first task pane add-in for Project 2013 by
// using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example uses addHandlerAsync to add an event handler for the ViewSelectionChanged event.
// When the active view changes, the handler checks the view type. It enables a button if the view is a resource
// view and disables the button if it isn't a resource view. Choosing the button gets the GUID of the selected
// resource and displays it in the add-in.
// The example assumes that your add-in has a reference to the jQuery library and that the following page controls
// are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" disabled="disabled" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            // Add a ViewSelectionChanged event handler.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            $('#get-info').click(getResourceGuid);

            // This example calls the handler on page load to get the active view
            // of the default page.
            getActiveView();
        });
    };

    // Activate the button based on the active view type of the document.
    // This is the ViewSelectionChanged event handler.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var viewType = result.value.viewType;
                    if (viewType == 6 ||   // ResourceForm
                        viewType == 7 ||   // ResourceSheet
                        viewType == 8 ||   // ResourceGraph
                        viewType == 15) {  // ResourceUsage
                        $('#get-info').removeAttr('disabled');
                    }
                    else {
                        $('#get-info').attr('disabled', 'disabled');
                    }
                    var output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    // Get the GUID of the currently selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html('Resource GUID: ' + result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For a complete code sample that shows how to use a ViewSelectionChanged event handler in a Project add-in,
// see "Create your first task pane add-in for Project by using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor

getActiveViewAsync(options, callback)

Returns the state of the current view of the presentation (edit or read).

getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<"edit" | "read">) => 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 state of the presentation's current view. The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides, such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View.

Returns
void
Remarks
Requirement SetsActiveView

Can trigger an event when the view changes.

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y

Examples

function getFileView() {
    // Get whether the current view is edit or read.
    Office.context.document.getActiveViewAsync(function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage(asyncResult.value);
        }
    });
}

getFileAsync(fileType, options, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult<Office.File>) => void): void;
Parameters
fileType
Office.FileType

The format in which the file will be returned

options
Office.GetFileOptions

Provides options for setting the size of slices that the document will be divided into.

callback
(result: AsyncResult<Office.File>) => 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 File object.

Returns
void
Remarks
Requirement SetsFile

For add-ins running in Office host applications other than Office for iOS, the getFileAsync method supports getting files in slices of up to 4194304 bytes (4 MB). For add-ins running in Office for iOS apps, the getFileAsync method supports getting files in slices of up to 65536 (64 KB).

The fileType parameter can be specified by using the Office.FileType enumeration or text values. But the possible values vary with the host:

Excel Online, Win32, Mac, and iOS: Office.FileType.Compressed

PowerPoint on Windows desktop, Mac, and iPad, and PowerPoint Online: Office.FileType.Compressed, Office.FileType.Pdf

Word on Windows desktop, Word on Mac, and Word Online: Office.FileType.Compressed, Office.FileType.Pdf, Office.FileType.Text

Word on iPad: Office.FileType.Compressed, Office.FileType.Text

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y Y

Examples

// The following example gets the document in Office Open XML ("compressed") format in 65536 bytes (64 KB) slices.
// Note: The implementation of app.showNotification in this example is from the Visual Studio template for Office Add-ins.
function getDocumentAsCompressed() {
    Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 /*64 KB*/ }, 
        function (result) {
            if (result.status == "succeeded") {
            // If the getFileAsync call succeeded, then
            // result.value will return a valid File Object.
            var myFile = result.value;
            var sliceCount = myFile.sliceCount;
            var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
            app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);

            // Get the file slices.
            getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
            }
            else {
            app.showNotification("Error:", result.error.message);
            }
    });
}

function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
    file.getSliceAsync(nextSlice, function (sliceResult) {
        if (sliceResult.status == "succeeded") {
            if (!gotAllSlices) { // Failed to get all slices, no need to continue.
                return;
            }

            // Got one slice, store it in a temporary array.
            // (Or you can do something else, such as
            // send it to a third-party server.)
            docdataSlices[sliceResult.value.index] = sliceResult.value.data;
            if (++slicesReceived == sliceCount) {
              // All slices have been received.
              file.closeAsync();
              onGotAllSlices(docdataSlices);
            }
            else {
                getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
            }
        }
            else {
                gotAllSlices = false;
                file.closeAsync();
                app.showNotification("getSliceAsync Error:", sliceResult.error.message);
            }
    });
}

function onGotAllSlices(docdataSlices) {
    var docdata = [];
    for (var i = 0; i < docdataSlices.length; i++) {
        docdata = docdata.concat(docdataSlices[i]);
    }

    var fileContent = new String();
    for (var j = 0; j < docdata.length; j++) {
        fileContent += String.fromCharCode(docdata[j]);
    }

    // Now all the file content is stored in 'fileContent' variable,
    // you can do something with it, such as print, fax...
}

// The following example gets the document in PDF format.
Office.context.document.getFileAsync(Office.FileType.Pdf,
    function(result) {
        if (result.status == "succeeded") {
            var myFile = result.value;
            var sliceCount = myFile.sliceCount;
            app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);
            // Now, you can call getSliceAsync to download the files,
            // as described in the previous code segment (compressed format).

            myFile.closeAsync();
        }
        else {
            app.showNotification("Error:", result.error.message);
        }
}
);

getFilePropertiesAsync(options, callback)

Gets file properties of the current document.

getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<Office.FileProperties>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

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

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 file's properties (with the URL found at asyncResult.value.url).

Returns
void
Remarks
Requirement SetsNot in a set

You get the file's URL with the url property asyncResult.value.url.

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y

Examples

// To read the URL of the current file, you need to write a callback function that returns the URL.
// The following example shows how to:
// 1. Pass an anonymous callback function that returns the value of the file's URL
//    to the callback parameter of the getFilePropertiesAsync method.
// 2. Display the value on the add-in's page.
function getFileUrl() {
    // Get the URL of the current file.
    Office.context.document.getFilePropertiesAsync(function (asyncResult) {
        var fileUrl = asyncResult.value.url;
        if (fileUrl == "") {
            showMessage("The file hasn't been saved yet. Save the file and try again");
        }
        else {
            showMessage(fileUrl);
        }
    });
}

getMaxResourceIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project 2016 on Windows desktop.

getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<number>) => 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 highest index number in the current project's resource collection.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getResourceTaskIndexAsync to get the maximum index of the collection 
// of resources in the current project. Then it uses the returned value and the getResourceByIndexAsync
// method to get each resource GUID. The example assumes that your add-in has a reference to the 
// jQuery library and that the following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    var resourceGuids = ;

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').click(getResourceInfo);
        });
    };

    // Get the maximum resource index, and then get the resource GUIDs.
    function getResourceInfo() {
        getMaxResourceIndex().then(
            function (data) {
                getResourceGuids(data);
            }
        );
    }

    // Get the maximum index of the resources for the current project.
    function getMaxResourceIndex() {
        var defer = $.Deferred();
        Office.context.document.getMaxResourceIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each resource GUID, and then display the GUIDs in the add-in.
    // There is no 0 index for resources, so start with index 1.
    function getResourceGuids(maxResourceIndex) {
        var defer = $.Deferred();
        for (var i = 1; i <= maxResourceIndex; i++) {
            getResourceGuid(i);
        }
        return defer.promise();
        function getResourceGuid(index) {
            Office.context.document.getResourceByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        resourceGuids.push(result.value);
                        if (index == maxResourceIndex) {
                            defer.resolve();
                            $('#message').html(resourceGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getMaxTaskIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project 2016 on Windows desktop.

getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<number>) => 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 highest index number in the current project's task collection.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getMaxTaskIndexAsync to get the maximum index
// of the collection of tasks in the current project. Then it uses the returned value
// with the getTaskByIndexAsync method to get each task GUID.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    var taskGuids = ;

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').click(getTaskInfo);
        });
    };

    // Get the maximum task index, and then get the task GUIDs.
    function getTaskInfo() {
        getMaxTaskIndex().then(
            function (data) {
                getTaskGuids(data);
            }
        );
    }

    // Get the maximum index of the tasks for the current project.
    function getMaxTaskIndex() {
        var defer = $.Deferred();
        Office.context.document.getMaxTaskIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each task GUID, and then display the GUIDs in the add-in.
    function getTaskGuids(maxTaskIndex) {
        var defer = $.Deferred();
        for (var i = 0; i <= maxTaskIndex; i++) {
            getTaskGuid(i);
        }
        return defer.promise();
        function getTaskGuid(index) {
            Office.context.document.getTaskByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        taskGuids.push(result.value);
                        if (index == maxTaskIndex) {
                            defer.resolve();
                            $('#message').html(taskGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getProjectFieldAsync(fieldId, options, callback)

Project documents only. Get Project field (Ex. ProjectWebAccessURL).

getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
fieldId
number

Project level fields.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<any>) => 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 contains the fieldValue property, which represents the value of the specified field.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example gets the values of three specified fields for the active project, 
// and then displays the values in the add-in.
// The example calls getProjectFieldAsync recursively, after the previous call returns successfully.
// It also tracks the calls to determine when all calls are sent.
// The example assumes your add-in has a reference to the jQuery library and that the 
// following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Get information for the active project.
            getProjectInformation();
        });
    };

    // Get the specified fields for the active project.
    function getProjectInformation() {
        var fields =
            [Office.ProjectProjectFields.Start, 
             Office.ProjectProjectFields.Finish, 
             Office.ProjectProjectFields.GUID];
        var fieldValues = ['Start: ', 'Finish: ', 'GUID: '];
        var index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == fields.length) {
                var output = '';
                for (var i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }
            else {
                Office.context.document.getProjectFieldAsync(
                    fields[index],
                    function (result) {

                        // If the call is successful, get the field value and then get the next field.
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getResourceByIndexAsync(resourceIndex, options, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project 2016 on Windows desktop.

getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
Parameters
resourceIndex
number

The index of the resource in the collection of resources for the project.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<string>) => 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 GUID of the resource as a string.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getMaxResourceIndexAsync to get the maximum index in the project's resource
// collection, and then calls getResourceByIndexAsync to get the GUID for each resource.
// The example assumes that your add-in has a reference to the jQuery library and that the following 
// page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    var resourceGuids = ;

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').click(getResourceInfo);
        });
    };

    // Get the maximum resource index, and then get the resource GUIDs.
    function getResourceInfo() {
        getMaxResourceIndex().then(
            function (data) {
                getResourceGuids(data);
            }
        );
    }

    // Get the maximum index of the resources for the current project.
    function getMaxResourceIndex() {
        var defer = $.Deferred();
        Office.context.document.getMaxResourceIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each resource GUID, and then display the GUIDs in the add-in.
    // There is no 0 index for resources, so start with index 1.
    function getResourceGuids(maxResourceIndex) {
        var defer = $.Deferred();
        for (var i = 1; i <= maxResourceIndex; i++) {
            getResourceGuid(i);
        }
        return defer.promise();
        function getResourceGuid(index) {
            Office.context.document.getResourceByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        resourceGuids.push(result.value);
                        if (index == maxResourceIndex) {
                            defer.resolve();
                            $('#message').html(resourceGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getResourceFieldAsync(resourceId, fieldId, options, callback)

Project documents only. Get resource field for provided resource Id. (Ex.ResourceName)

getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
Parameters
resourceId
string

Either a string or value of the Resource Id.

fieldId
number

Resource Fields.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<string>) => 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 GUID of the resource as a string.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource
// that's currently selected in a resource view. Then it gets three resource field values by calling 
// getResourceFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following 
// page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getResourceInfo);
        });
    };

    // Get the GUID of the resource and then get the resource fields.
    function getResourceInfo() {
        getResourceGuid().then(
            function (data) {
                getResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected resource.
    function getResourceFields(resourceGuid) {
        var targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        var fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        var index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                var output = '';
                for (var i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // If the call is successful, get the field value and then get the next field.
            else {
                Office.context.document.getResourceFieldAsync(
                    resourceGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedDataAsync(coerciontype, options, callback)

Reads the data contained in the current selection in the document.

getSelectedDataAsync<T>(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult<T>) => void): void;
Parameters
coerciontype
Office.CoercionType
options
Office.GetSelectedDataOptions

Provides options for customizing what data is returned and how it is formatted.

callback
(result: 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 data in the current selection. This is returned in the data structure or format you specified with the coercionType parameter. (See Remarks for more information about data coercion.)

Returns
void
Remarks
Requirement SetsSelection

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

Property Use to...
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 A user-defined item of any type that is returned in the AsyncResult object without being altered.

The possible values for the Office.CoercionType parameter vary by the host.

Host Supported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online Office.CoercionType.Text (string)
Excel, Word, and Word Online Office.CoercionType.Matrix (array of arrays)
Access, Excel, Word, and Word Online Office.CoercionType.Table (TableData object)
Word Office.CoercionType.Html
Word and Word Online Office.CoercionType.Ooxml (Office Open XML)
PowerPoint and PowerPoint Online Office.CoercionType.SlideRange

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Project Y Y
Word Y Y

Examples

// The following example uses the getSelectedDataAsync method of the Document object to retrieve the
// user's current selection as text, and then display it in the add-in's page.

// Display the user's current selection.
function showSelection() {
    Office.context.document.getSelectedDataAsync(
        "text",                        // coercionType
        {valueFormat: "unformatted",   // valueFormat
        filterType: "all"},            // filterType
        function (result) {            // callback
            var dataValue; 
            dataValue = result.value;
            write('Selected data is: ' + dataValue);
        });
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// To read the value of the current selection, you need to write a callback function that reads the selection.
// The following example shows how to:
// 1. Pass an anonymous callback function that reads the value of the current selection
//    to the callback parameter of the getSelectedDataAsync method.
// 2. Read the selection as text, unformatted, and not filtered.
// 3. Display the value on the add-in's page.
function getText() {
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text, 
        { valueFormat: "unformatted", filterType: "all" },
        function (asyncResult) {
            var error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                write(error.name + ": " + error.message);
            } 
            else {
                // Get selected data.
                var dataValue = asyncResult.value; 
                write('Selected data is ' + dataValue);
            }            
        });
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following code example gets the values of the selected cells. It uses the optional
// asyncContext parameter to pass some text to the callback function.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getSelectedText);
        });
    };

    // Get the text from the selected cells in the document, and display it in the add-in.
    function getSelectedText() {
        Office.context.document.getSelectedDataAsync(
            Office.CoercionType.Text,
            {asyncContext: 'Some related info'},
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var output = String.format(
                        'Selected text: {0}<br/>Passed info: {1}',
                        result.value, result.asyncContext);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedResourceAsync(options, callback)

Project documents only. Get the current selected Resource's Id.

getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<string>) => 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 GUID of the resource as a string.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource that's 
// currently selected in a resource view. Then it gets three resource field values by calling 
// getResourceFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following page controls are
// defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getResourceInfo);
        });
    };

    // Get the GUID of the resource and then get the resource fields.
    function getResourceInfo() {
        getResourceGuid().then(
            function (data) {
                getResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected resource.
    function getResourceFields(resourceGuid) {
        var targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        var fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        var index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                var output = '';
                for (var i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // If the call is successful, get the field value and then get the next field.
            else {
                Office.context.document.getResourceFieldAsync(
                    resourceGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedTaskAsync(options, callback)

Project documents only. Get the current selected Task's Id.

getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<string>) => 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 GUID of the resource as a string.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's currently
// selected in a task view. Then it gets task properties by calling getTaskAsync.
// The example assumes your add-in has a reference to the jQuery library and that the following page
// controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getTaskInfo);
        });
    };

    // // Get the GUID of the task, and then get local task properties.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskProperties(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get local properties for the selected task, and then display it in the add-in.
    function getTaskProperties(taskGuid) {
        Office.context.document.getTaskAsync(
            taskGuid,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var taskInfo = result.value;
                    var output = String.format(
                        'Name: {0}<br/>GUID: {1}<br/>SharePoint task ID: {2}<br/>Resource names: {3}',
                        taskInfo.taskName, taskGuid, taskInfo.wssTaskId, taskInfo.resourceNames);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedViewAsync(options, callback)

Project documents only. Get the current selected View Type (Ex. Gantt) and View Name.

getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<any>) => 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 contains the following properties: viewName - The name of the view, as a ProjectViewTypes constant. viewType - The type of view, as the integer value of a ProjectViewTypes constant.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls adds a ViewSelectionChanged event handler that
// calls getSelectedViewAsync to get the name and type of the active view in the document.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            getActiveView();
        });
    };

    // Get the active view's name and type.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskAsync(taskId, options, callback)

Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId.

getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
taskId
string

Either a string or value of the Task Id.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<any>) => 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 contains the following properties: taskName - The name of the task. wssTaskId - The ID of the task in the synchronized SharePoint task list. If the project is not synchronized with a SharePoint task list, the value is 0. resourceNames - The comma-separated list of the names of resources that are assigned to the task.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedTaskAsync to get the task GUID of the currently
// selected task. Then it calls getTaskAsync to get the properties for the task that are
// available from the JavaScript API for Office.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getTaskInfo);
        });
    };

    // Get the GUID of the task, and then get local task properties.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskProperties(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get local properties for the selected task, and then display it in the add-in.
    function getTaskProperties(taskGuid) {
        Office.context.document.getTaskAsync(
            taskGuid,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    var taskInfo = result.value;
                    var output = String.format(
                        'Name: {0}<br/>GUID: {1}<br/>SharePoint task ID: {2}<br/>Resource names: {3}',
                        taskInfo.taskName, taskGuid, taskInfo.wssTaskId, taskInfo.resourceNames);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskByIndexAsync(taskIndex, options, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project 2016 on Windows desktop.

getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;
Parameters
taskIndex
number

The index of the task in the collection of tasks for the project.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<string>) => 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 GUID of the task as a string.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getMaxTaskIndexAsync to get the
// maximum index in the project's task collection, and then
// calls getTaskByIndexAsync to get the GUID for each task.
// The example assumes that your add-in has a reference to the
// jQuery library and that the following page controls are defined
// in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    var taskGuids = ;

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').click(getTaskInfo);
        });
    };

    // Get the maximum task index, and then get the task GUIDs.
    function getTaskInfo() {
        getMaxTaskIndex().then(
            function (data) {
                getTaskGuids(data);
            }
        );
    }

    // Get the maximum index of the tasks for the current project.
    function getMaxTaskIndex() {
        var defer = $.Deferred();
        Office.context.document.getMaxTaskIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each task GUID, and then display the GUIDs in the add-in.
    function getTaskGuids(maxTaskIndex) {
        var defer = $.Deferred();
        for (var i = 0; i <= maxTaskIndex; i++) {
            getTaskGuid(i);
        }
        return defer.promise();
        function getTaskGuid(index) {
            Office.context.document.getTaskByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        taskGuids.push(result.value);
                        if (index == maxTaskIndex) {
                            defer.resolve();
                            $('#message').html(taskGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskFieldAsync(taskId, fieldId, options, callback)

Project documents only. Get task field for provided task Id. (Ex. StartDate).

getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
taskId
string

Either a string or value of the Task Id.

fieldId
number

Task Fields.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<any>) => 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 contains the fieldValue property, which represents the value of the specified field.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's currently
// selected in a task view. Then it gets two task field values by calling getTaskFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following page
// controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').click(getTaskInfo);
        });
    };

    // Get the GUID of the task, and then get the task fields.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskFields(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected task.
    function getTaskFields(taskGuid) {
        var output = '';
        var targetFields = [Office.ProjectTaskFields.Priority, Office.ProjectTaskFields.PercentComplete];
        var fieldValues = ['Priority: ', '% Complete: '];
        var index = 0;
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                for (var i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // Get the field value. If the call is successful, then get the next field.
            else {
                Office.context.document.getTaskFieldAsync(
                    taskGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getWSSUrlAsync(options, callback)

Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too.

getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<any>) => 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 contains the following properties: listName - the name of the synchronized SharePoint task list. serverUrl - the URL of the synchronized SharePoint task list.

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

goToByIdAsync(id, goToType, options, callback)

Goes to the specified object or location in the document.

goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult<any>) => void): void;
Parameters
id
string | number

The identifier of the object or location to go to.

goToType
Office.GoToType

The type of the location to go to.

options
Office.GoToByIdOptions

Provides options for whether to select the location that is navigated to.

callback
(result: AsyncResult<any>) => 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 current view.

Returns
void
Remarks
Requirement Setsnot in a set

PowerPoint doesn't support the goToByIdAsync method in Master Views.

The behavior caused by the selectionMode option varies by host:

In Excel: Office.SelectionMode.Selected selects all content in the binding, or named item. Office.SelectionMode.None for text bindings, selects the cell; for matrix bindings, table bindings, and named items, selects the first data cell (not first cell in header row for tables).

In PowerPoint: Office.SelectionMode.Selected selects the slide title or first textbox on the slide. Office.SelectionMode.None doesn't select anything.

In Word: Office.SelectionMode.Selected selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables).

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y

Examples

// Go to a binding by id (Word and Excel)
// The following example shows how to:
// 1. Create a table binding using the addFromSelectionAsync method as a sample binding to work with.
// 2. Specify that binding as the binding to go to.
// 3. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 4. Display the value on the add-in's page.
function gotoBinding() {
    // Create a new table binding for the selected table.
    Office.context.document.bindings.addFromSelectionAsync("table",{ id: "MyTableBinding" }, function (asyncResult) {
    if (asyncResult.status == "failed") {
              showMessage("Action failed with error: " + asyncResult.error.message);
          }
          else {
              showMessage("Added new binding with type: " + asyncResult.value.type +" and id: " + asyncResult.value.id);
          }
    });

    // Go to binding by id.
    Office.context.document.goToByIdAsync("MyTableBinding", Office.GoToType.Binding, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

// Go to a table in a spreadsheet (Excel)
// The following example shows how to:
// 1. Specify a table by name as the table to go to.
// 2. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 3. Display the value on the add-in's page.
function goToTable() {
    Office.context.document.goToByIdAsync("Table1", Office.GoToType.NamedItem, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

// Go to the currently selected slide by id (PowerPoint)
// The following example shows how to:
// 1. Get the id of the currently selected slides using the getSelectedDataAsync method.
// 2. Specify the returned id as the slide to go to.
// 3. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 4. Display the value of the stringified JSON object returned by asyncResult.value,
//    which contains information about the selected slides, on the add-in's page.
var firstSlideId = 0;
function gotoSelectedSlide() {
    //Get currently selected slide's id
    Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            firstSlideId = asyncResult.value.slides[0].id;
            app.showNotification(JSON.stringify(asyncResult.value));
        }
    });
    //Go to slide by id.
    Office.context.document.goToByIdAsync(firstSlideId, Office.GoToType.Slide, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            app.showNotification("Navigation successful");
        }
    });
}

// Go to slide by index (PowerPoint)
// The following example shows how to:
// 1. Specify the index of the first, last, previous, or next slide to go to.
// 2. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 3. Display the value on the add-in's page.
function goToSlideByIndex() {
    var goToFirst = Office.Index.First;
    var goToLast = Office.Index.Last;
    var goToPrevious = Office.Index.Previous;
    var goToNext = Office.Index.Next;

    Office.context.document.goToByIdAsync(goToNext, Office.GoToType.Index, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

removeHandlerAsync(eventType, options, callback)

Removes an event handler 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 document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'.

options
Office.RemoveHandlerOptions

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

callback
(result: 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 SetsDocumentEvents

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y

Examples

// The following example removes the event handler named 'MyHandler'.
function removeSelectionChangedEventHandler() {
    Office.context.document.removeHandlerAsync(Office.EventType.DocumentSelectionChanged, {handler:MyHandler});
}

function MyHandler(eventArgs) {
    doSomethingWithDocument(eventArgs.document);
}
// The following code example uses addHandlerAsync to add an event handler for the
// ResourceSelectionChanged event and removeHandlerAsync to remove the handler.
// When a resource is selected in a resource view, the handler displays the
// resource GUID. When the handler is removed, the GUID is not displayed.
// The example assumes that your add-in has a reference to the jQuery library and
// that the following page control is defined in the content div in the page body:
// <input id="remove-handler" type="button" value="Remove handler" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ResourceSelectionChanged,
                getResourceGuid);
            $('#remove-handler').click(removeEventHandler);
        });
    };

    // Remove the event handler.
    function removeEventHandler() {
        Office.context.document.removeHandlerAsync(
            Office.EventType.ResourceSelectionChanged,
            {handler:getResourceGuid,
            asyncContext:'The handler is removed.'},
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#remove-handler').attr('disabled', 'disabled');
                    $('#message').html(result.asyncContext);
                }
            }
        );
    }

    // Get the GUID of the currently selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html('Resource GUID: ' + result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

setResourceFieldAsync(resourceId, fieldId, fieldValue, options, callback)

Project documents only. Set resource field for specified resource Id.

Important: This API works only in Project 2016 on Windows desktop.

setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
Parameters
resourceId
string

Either a string or value of the Resource Id.

fieldId
number

Resource Fields.

fieldValue
string | number | boolean | object

Value of the target field.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<void>) => void

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

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource that's
// currently selected in a resource view. Then it sets two resource field values by calling
// setResourceFieldAsync recursively.
// The getSelectedTaskAsync method used in the example requires that a task view
// (for example, Task Usage) is the active view and that a task is selected. See the addHandlerAsync
// method for an example that activates a button based on the active view type.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="set-info" type="button" value="Set info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#set-info').click(setResourceInfo);
        });
    };

    // Get the GUID of the resource, and then get the resource fields.
    function setResourceInfo() {
        getResourceGuid().then(
            function (data) {
                setResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Set the specified fields for the selected resource.
    function setResourceFields(resourceGuid) {
        var targetFields = [Office.ProjectResourceFields.StandardRate, Office.ProjectResourceFields.Notes];
        var fieldValues = [.28, 'Notes for the resource.'];

        // Set the field value. If the call is successful, set the next field.
        for (var i = 0; i < targetFields.length; i++) {
            Office.context.document.setResourceFieldAsync(
                resourceGuid,
                targetFields[i],
                fieldValues[i],
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        i++;
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
        $('#message').html('Field values set');
    }

    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

setSelectedDataAsync(data, options, callback)

Writes the specified data into the current selection.

setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult<void>) => void): void;
Parameters
data
string | TableData | any[][]

The data to be set. Either a string or Office.CoercionType value, 2d array or TableData object.

If the value passed for data is:

  • A string: Plain text or anything that can be coerced to a string will be inserted. In Excel, you can also specify data as a valid formula to add that formula to the selected 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 Document.getSelectedDataAsync method on the selected 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"): Tabular data without headers will be inserted. 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"]]

In Excel, you can also specify data as an array of arrays that contains valid formulas to add them to the selected cells. For example if no other data will be overwritten, setting data to [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] will add those two formulas to the selection. Just as when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been set - you can only read the formulas' results.

  • A TableData object: A table with headers will be inserted. In Excel, 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 selected 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".
options
Office.SetSelectedDataOptions

Provides options for how to insert data to the selection.

callback
(result: AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The AsyncResult.value property always returns undefined because there is no object or data to retrieve.

Returns
void
Remarks
Requirement SetsSelection

Application-specific behaviors

The following application-specific actions apply when writing data to a selection.

WordIf there is no selection and the insertion point is at a valid location, the specified data is inserted at the insertion pointIf data is a string, the specified text is inserted.
If data is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
If data is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).
If data is Office Open XML, the specified XML is inserted.
If data is a base64 encoded image stream, the specified image is inserted.
If there is a selectionIt will be replaced with the specified data following the same rules as above.
Insert imagesInserted images are placed inline. The imageLeft and imageTop parameters are ignored. The image aspect ratio is always locked. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
ExcelIf a single cell is selectedIf data is a string, the specified text is inserted as the value of the current cell.
If data is an array of arrays ("matrix"), the specified set of rows and columns are inserted, if no other data in surrounding cells will be overwritten.
If data is a TableData object, a new Excel table with the specified set of rows and headers is inserted, if no other data in surrounding cells will be overwritten.
If multiple cells are selectedIf the shape does not match the shape of data, an error is returned.
If the shape of the selection exactly matches the shape of data, the values of the selected cells are updated based on the values in data.
Insert imagesInserted images are floating. The position imageLeft and imageTop parameters are relative to currently selected cell(s). Negative imageLeft and imageTop values are allowed and possibly readjusted by Excel to position the image inside a worksheet. Image aspect ratio is locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
All other casesAn error is returned.
Excel OnlineIn addition to the behaviors described for Excel above, these limits apply when writing data in Excel OnlineThe total number of cells you can write to a worksheet with 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.
PowerPointInsert imageInserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.

The possible values for the Office.CoercionType parameter vary by the host.

Host Supported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online Office.CoercionType.Text (string)
Excel, Word, and Word Online Office.CoercionType.Matrix (array of arrays)
Access, Excel, Word, and Word Online Office.CoercionType.Table (TableData object)
Word Office.CoercionType.Html
Word and Word Online Office.CoercionType.Ooxml (Office Open XML)
PowerPoint and PowerPoint Online Office.CoercionType.SlideRange

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser) Office for iPad
Access y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y

Examples

// The following example sets the selected text or cell to "Hello World!", 
// and if that fails, displays the value of the error.message property.
function writeText() {
    Office.context.document.setSelectedDataAsync("Hello World!",
        function (asyncResult) {
            var error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed){
                write(error.name + ": " + error.message);
            }
        });
}

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

// Specifying the optional coercionType parameter lets you specify the kind of data you want to write
// to a selection. The following example writes data as an array of three rows of two columns, 
// specifying the coercionType as "matrix" for that data structure, and if that fails, 
// displays the value of the error.message property.
function writeMatrix() {
    Office.context.document.setSelectedDataAsync(
        [["Red", "Rojo"], ["Green", "Verde"], ["Blue", "Azul"]],
        {coercionType: Office.CoercionType.Matrix}
        function (asyncResult) {
            var error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed){
                write(error.name + ": " + error.message);
            }
        });
}

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

// The following example writes data as a one column table with a header and four rows, 
// specifying the coercionType as "table" for that data structure, and if that fails, 
// displays the value of the error.message property.
function writeTable() {
    // Build table.
    var myTable = new Office.TableData();
    myTable.headers = [["Cities"]];
    myTable.rows = [['Berlin'], ['Roma'], ['Tokyo'], ['Seattle']];

    // Write table.
    Office.context.document.setSelectedDataAsync(myTable, {coercionType: Office.CoercionType.Table},
        function (result) {
            var error = result.error
            if (result.status === Office.AsyncResultStatus.Failed) {
                write(error.name + ": " + error.message);
            }
    });
}

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

// In Word if you want to write HTML to the selection, 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.context.document.setSelectedDataAsync(
        "<b>Hello</b> World!", {coercionType: Office.CoercionType.Html}, function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.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 Word, PowerPoint, or Excel, if you want to write an image to the selection, you can specify the coercionType
// parameter as "image" as shown in the following example. Note that imageLeft and imageTop are ignored by Word.
function insertPictureAtSelection(base64EncodedImageStr) {

    Office.context.document.setSelectedDataAsync(base64EncodedImageStr, {
    coercionType: Office.CoercionType.Image,
    imageLeft: 50,
    imageTop: 50,
    imageWidth: 100,
    imageHeight: 100
    },
    function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            console.log("Action failed with error: " + asyncResult.error.message);
        }
    });
}

setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)

Project documents only. Set task field for specified task Id.

Important: This API works only in Project 2016 on Windows desktop.

setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;
Parameters
taskId
string

Either a string or value of the Task Id.

fieldId
number

Task Fields.

fieldValue
string | number | boolean | object

Value of the target field.

options
Office.AsyncContextOptions

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

callback
(result: AsyncResult<void>) => void

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

Returns
void
Remarks

Support details

A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method.

For more information about Office host application and server requirements, see Requirements for running Office Add-ins.

Supported hosts, by platform

Office for Windows desktop Office Online (in browser)
Project Y

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's
// currently selected in a task view. Then it sets two task field values by calling
// setTaskFieldAsync recursively.
// The getSelectedTaskAsync method used in the example requires that a task view
// (for example, Task Usage) is the active view and that a task is selected. See the
// addHandlerAsync method for an example that activates a button based on the active view type.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="set-info" type="button" value="Set info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#set-info').click(setTaskInfo);
        });
    };

    // Get the GUID of the task, and then get the task fields.
    function setTaskInfo() {
        getTaskGuid().then(
            function (data) {
                setTaskFields(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        var defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Set the specified fields for the selected task.
    function setTaskFields(taskGuid) {
        var targetFields = [Office.ProjectTaskFields.Active, Office.ProjectTaskFields.Notes];
        var fieldValues = [true, 'Notes for the task.'];

        // Set the field value. If the call is successful, set the next field.
        for (var i = 0; i < targetFields.length; i++) {
            Office.context.document.setTaskFieldAsync(
                taskGuid,
                targetFields[i],
                fieldValues[i],
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        i++;
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
        $('#message').html('Field values set');
    }

    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();