Office.Document interface

Uma classe abstrata que representa o documento com o qual o suplemento está interagindo.

Comentários

Aplicativos: Excel, PowerPoint, Project, Word

Exemplos

// Get the Document object with the Common APIs.
const document : Office.Document = Office.context.document;

Propriedades

bindings

Obtém um objeto que fornece acesso às associações definidas no documento.

customXmlParts

Obtém um objeto que representa as partes XML personalizadas no documento.

mode

Obtém o modo em que o documento está.

settings

Obtém um objeto que representa as configurações personalizadas salvas do suplemento de painel de tarefas ou conteúdo para o documento atual.

url

Obtém a URL do documento que o aplicativo do Office está aberto no momento. Retornará nulo se a URL não estiver disponível.

Métodos

addHandlerAsync(eventType, handler, options, callback)

Adiciona um manipulador de eventos para um evento de objeto Document.

addHandlerAsync(eventType, handler, callback)

Adiciona um manipulador de eventos para um evento de objeto Document.

getActiveViewAsync(options, callback)

Retorna o estado do modo de exibição atual da apresentação (edição ou leitura).

getActiveViewAsync(callback)

Retorna o estado do modo de exibição atual da apresentação (edição ou leitura).

getFileAsync(fileType, options, callback)

Retorna o arquivo de documento inteiro em fatias de até 4194304 bytes (4 MB). Para suplementos no iPad, há suporte para fatia de arquivo até 65536 (64 KB). Observe que a especificação do tamanho de fatia do arquivo acima do limite permitido resultará em uma falha de “Erro interno”.

getFileAsync(fileType, callback)

Retorna o arquivo de documento inteiro em fatias de até 4194304 bytes (4 MB). Para suplementos no iPad, há suporte para fatia de arquivo até 65536 (64 KB). Observe que a especificação do tamanho de fatia do arquivo acima do limite permitido resultará em uma falha de “Erro interno”.

getFilePropertiesAsync(options, callback)

Obtém as propriedades de arquivo do documento atual.

getFilePropertiesAsync(callback)

Obtém as propriedades de arquivo do documento atual.

getMaxResourceIndexAsync(options, callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de recursos no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getMaxResourceIndexAsync(callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de recursos no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getMaxTaskIndexAsync(options, callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de tarefas no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getMaxTaskIndexAsync(callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de tarefas no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getProjectFieldAsync(fieldId, options, callback)

Somente documentos do projeto. Obter o campo Project (por exemplo, ProjectWebAccessURL).

getProjectFieldAsync(fieldId, callback)

Somente documentos do projeto. Obter o campo Project (por exemplo, ProjectWebAccessURL).

getResourceByIndexAsync(resourceIndex, options, callback)

Somente documentos do projeto. Obtenha o GUID do recurso que tem o índice especificado na coleção de recursos.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getResourceByIndexAsync(resourceIndex, callback)

Somente documentos do projeto. Obtenha o GUID do recurso que tem o índice especificado na coleção de recursos.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getResourceFieldAsync(resourceId, fieldId, options, callback)

Somente documentos do projeto. Obtenha o campo de recursos para a ID do recurso fornecida. (por exemplo, ResourceName)

getResourceFieldAsync(resourceId, fieldId, callback)

Somente documentos do projeto. Obtenha o campo de recursos para a ID do recurso fornecida. (por exemplo, ResourceName)

getSelectedDataAsync(coercionType, options, callback)

Lê os dados contidos na seleção atual no documento.

getSelectedDataAsync(coercionType, callback)

Lê os dados contidos na seleção atual no documento.

getSelectedResourceAsync(options, callback)

Somente documentos do projeto. Obtenha a ID do recurso selecionado atualmente.

getSelectedResourceAsync(callback)

Somente documentos do projeto. Obtenha a ID do recurso selecionado atualmente.

getSelectedTaskAsync(options, callback)

Somente documentos do projeto. Obtenha a ID da Tarefa selecionada atualmente.

getSelectedTaskAsync(callback)

Somente documentos do projeto. Obtenha a ID da Tarefa selecionada atualmente.

getSelectedViewAsync(options, callback)

Somente documentos do projeto. Obtenha o tipo de exibição selecionado atual (por exemplo, Gantt) e o Nome de Exibição.

getSelectedViewAsync(callback)

Somente documentos do projeto. Obtenha o tipo de exibição selecionado atual (por exemplo, Gantt) e o Nome de Exibição.

getTaskAsync(taskId, options, callback)

Somente documentos do projeto. Obtenha o Nome da Tarefa, A ID da Tarefa WSS e ResourceNames para determinado taskId.

getTaskAsync(taskId, callback)

Somente documentos do projeto. Obtenha o Nome da Tarefa, A ID da Tarefa WSS e ResourceNames para determinado taskId.

getTaskByIndexAsync(taskIndex, options, callback)

Somente documentos do projeto. Obtenha o GUID da tarefa que tem o índice especificado na coleção de tarefas.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getTaskByIndexAsync(taskIndex, callback)

Somente documentos do projeto. Obtenha o GUID da tarefa que tem o índice especificado na coleção de tarefas.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getTaskFieldAsync(taskId, fieldId, options, callback)

Somente documentos do projeto. Obtenha o campo de tarefas para a ID da tarefa fornecida. (por exemplo, StartDate).

getTaskFieldAsync(taskId, fieldId, callback)

Somente documentos do projeto. Obtenha o campo de tarefas para a ID da tarefa fornecida. (por exemplo, StartDate).

getWSSUrlAsync(options, callback)

Somente documentos do projeto. Obtenha a URL do WSS e o nome da lista para a Lista de Tarefas, o MPP também está sincronizado.

getWSSUrlAsync(callback)

Somente documentos do projeto. Obtenha a URL do WSS e o nome da lista para a Lista de Tarefas, o MPP também está sincronizado.

goToByIdAsync(id, goToType, options, callback)

Vai para o objeto ou local especificado no documento.

goToByIdAsync(id, goToType, callback)

Vai para o objeto ou local especificado no documento.

removeHandlerAsync(eventType, options, callback)

Remove um manipulador de eventos para o tipo de evento especificado.

removeHandlerAsync(eventType, callback)

Remove um manipulador de eventos para o tipo de evento especificado.

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

Somente documentos do projeto. Defina o campo de recursos para a ID de recurso especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Somente documentos do projeto. Defina o campo de recursos para a ID de recurso especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

setSelectedDataAsync(data, options, callback)

Grava os dados especificados na seleção atual.

setSelectedDataAsync(data, callback)

Grava os dados especificados na seleção atual.

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

Somente documentos do projeto. Defina o campo de tarefas para a ID da tarefa especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Somente documentos do projeto. Defina o campo de tarefas para a ID da tarefa especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

Detalhes da propriedade

bindings

Obtém um objeto que fornece acesso às associações definidas no documento.

bindings: Bindings;

Valor da propriedade

Comentários

Você não instancia o objeto Document diretamente em seu script. Para chamar membros do objeto Document para interagir com o documento ou planilha atual, use Office.context.document no script.

Exemplos

function displayAllBindings() {
    Office.context.document.bindings.getAllAsync(function (asyncResult) {
        let bindingString = '';
        for (let i in asyncResult.value) {
            bindingString += asyncResult.value[i].id + '\n';
        }
        write('Existing bindings: ' + bindingString);
    });
}

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

customXmlParts

Obtém um objeto que representa as partes XML personalizadas no documento.

customXmlParts: CustomXmlParts;

Valor da propriedade

Exemplos

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

Obtém o modo em que o documento está.

mode: DocumentMode;

Valor da propriedade

Exemplos

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() {
        const 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

Obtém um objeto que representa as configurações personalizadas salvas do suplemento de painel de tarefas ou conteúdo para o documento atual.

settings: Settings;

Valor da propriedade

url

Obtém a URL do documento que o aplicativo do Office está aberto no momento. Retornará nulo se a URL não estiver disponível.

url: string;

Valor da propriedade

string

Exemplos

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; 
}

Detalhes do método

addHandlerAsync(eventType, handler, options, callback)

Adiciona um manipulador de eventos para um evento de objeto Document.

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

Parâmetros

eventType
Office.EventType

Para um evento de objeto Document, o parâmetro eventType pode ser especificado como Office.EventType.Document.SelectionChanged ou Office.EventType.Document.ActiveViewChanged, ou o valor de texto correspondente dessa enumeração.

handler

any

A função manipulador de eventos a ser adicionada, cujo único parâmetro é do tipo Office.DocumentSelectionChangedEventArgs. Obrigatório.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Comentários

Conjunto de requisitos: DocumentEvents

Você pode adicionar vários manipuladores de eventos para o eventType especificado desde que o nome de cada função do manipulador de eventos seja exclusivo.

addHandlerAsync(eventType, handler, callback)

Adiciona um manipulador de eventos para um evento de objeto Document.

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

Parâmetros

eventType
Office.EventType

Para um evento de objeto Document, o parâmetro eventType pode ser especificado como Office.EventType.Document.SelectionChanged ou Office.EventType.Document.ActiveViewChanged, ou o valor de texto correspondente dessa enumeração.

handler

any

A função manipulador de eventos a ser adicionada, cujo único parâmetro é do tipo Office.DocumentSelectionChangedEventArgs. Obrigatório.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Comentários

Conjunto de requisitos: DocumentEvents

Você pode adicionar vários manipuladores de eventos para o eventType especificado desde que o nome de cada função do manipulador de eventos seja exclusivo.

Exemplos

// 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 Microsoft Project".
// https://learn.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 {
                    const 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 Microsoft Project".
// https://learn.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').on("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 {
                    const 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');
                    }
                    const 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://learn.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor

getActiveViewAsync(options, callback)

Retorna o estado do modo de exibição atual da apresentação (edição ou leitura).

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

(result: Office.AsyncResult<"edit" | "read">) => void

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o estado da exibição atual da apresentação. O valor retornado pode ser "editar" ou "ler". "editar" corresponde a qualquer uma das exibições em que você pode editar slides: Normal, Classificador de Slides ou Modo de Exibição de Contorno. "read" corresponde à Apresentação de Slides ou à Exibição de Leitura.

Retornos

void

Comentários

Conjunto de requisitos: ActiveView

Pode disparar um evento quando o modo de exibição for alterado.

getActiveViewAsync(callback)

Retorna o estado do modo de exibição atual da apresentação (edição ou leitura).

getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void;

Parâmetros

callback

(result: Office.AsyncResult<"edit" | "read">) => void

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o estado da exibição atual da apresentação. O valor retornado pode ser "editar" ou "ler". "editar" corresponde a qualquer uma das exibições em que você pode editar slides: Normal, Classificador de Slides ou Modo de Exibição de Contorno. "read" corresponde à Apresentação de Slides ou à Exibição de Leitura.

Retornos

void

Comentários

Conjunto de requisitos: ActiveView

Pode disparar um evento quando o modo de exibição for alterado.

Exemplos

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)

Retorna o arquivo de documento inteiro em fatias de até 4194304 bytes (4 MB). Para suplementos no iPad, há suporte para fatia de arquivo até 65536 (64 KB). Observe que a especificação do tamanho de fatia do arquivo acima do limite permitido resultará em uma falha de “Erro interno”.

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

Parâmetros

fileType
Office.FileType

O formato no qual o arquivo será retornado

options
Office.GetFileOptions

Fornece opções para definir o tamanho das fatias em que o documento será dividido.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o objeto File.

Retornos

void

Comentários

Conjuntos de requisitos:

Para suplementos em execução em aplicativos do Office que não sejam o Office no iPad, o getFileAsync método dá suporte à obtenção de arquivos em fatias de até 4194304 bytes (4 MB). Para suplementos em execução em aplicativos do Office no iPad, o getFileAsync método dá suporte à obtenção de arquivos em fatias de até 65536 (64 KB).

O fileType parâmetro pode ser especificado usando os valores de texto ou enumeração Office.FileType . Mas os valores possíveis variam com o aplicativo.

FileTypes com suporte, por plataforma

Office na Web Office no Windows Office no Mac Office no iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text Sem suporte
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

Exemplos

// 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.
                const myFile = result.value;
                const sliceCount = myFile.sliceCount;
                const docDataSlices = [];
                let slicesReceived = 0, gotAllSlices = true;
                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) {
    let docData = [];
    for (let i = 0; i < docDataSlices.length; i++) {
        docData = docData.concat(docDataSlices[i]);
    }

    let fileContent = new String();
    for (let 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") {
            const myFile = result.value;
            const sliceCount = myFile.sliceCount;
            app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);

            // Get the file slices.
            const docDataSlices = [];
            let slicesReceived = 0, gotAllSlices = true;
            getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docDataSlices, slicesReceived);
            
            myFile.closeAsync();
        }
        else {
            app.showNotification("Error:", result.error.message);
        }
    }
);

getFileAsync(fileType, callback)

Retorna o arquivo de documento inteiro em fatias de até 4194304 bytes (4 MB). Para suplementos no iPad, há suporte para fatia de arquivo até 65536 (64 KB). Observe que a especificação do tamanho de fatia do arquivo acima do limite permitido resultará em uma falha de “Erro interno”.

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

Parâmetros

fileType
Office.FileType

O formato no qual o arquivo será retornado

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o objeto File.

Retornos

void

Comentários

Conjuntos de requisitos:

Para suplementos em execução em aplicativos do Office que não sejam o Office no iPad, o getFileAsync método dá suporte à obtenção de arquivos em fatias de até 4194304 bytes (4 MB). Para suplementos em execução em aplicativos do Office no iPad, o getFileAsync método dá suporte à obtenção de arquivos em fatias de até 65536 (64 KB).

O fileType parâmetro pode ser especificado usando os valores de texto ou enumeração Office.FileType . Mas os valores possíveis variam com o aplicativo.

FileTypes com suporte, por plataforma

Office na Web Office no Windows Office no Mac Office no iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text Sem suporte
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

getFilePropertiesAsync(options, callback)

Obtém as propriedades de arquivo do documento atual.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é as propriedades do arquivo (com a URL encontrada em asyncResult.value.url).

Retornos

void

Comentários

Conjuntos de requisitos: não em um conjunto

Você obtém a URL do arquivo com a propriedade asyncResult.value.urlurl .

getFilePropertiesAsync(callback)

Obtém as propriedades de arquivo do documento atual.

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

Parâmetros

callback

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

Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é as propriedades do arquivo (com a URL encontrada em asyncResult.value.url).

Retornos

void

Comentários

Conjuntos de requisitos: não em um conjunto

Você obtém a URL do arquivo com a propriedade asyncResult.value.urlurl .

Exemplos

// 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) {
        const 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)

Somente documentos do projeto. Obtenha o índice máximo da coleção de recursos no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o número de índice mais alto na coleção de recursos do projeto atual.

Retornos

void

getMaxResourceIndexAsync(callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de recursos no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getMaxResourceIndexAsync(callback?: (result: AsyncResult<number>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o número de índice mais alto na coleção de recursos do projeto atual.

Retornos

void

Exemplos

// 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";
    const 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').on("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() {
        const 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) {
        const defer = $.Deferred();
        for (let 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)

Somente documentos do projeto. Obtenha o índice máximo da coleção de tarefas no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o número de índice mais alto na coleção de tarefas do projeto atual.

Retornos

void

getMaxTaskIndexAsync(callback)

Somente documentos do projeto. Obtenha o índice máximo da coleção de tarefas no projeto atual.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getMaxTaskIndexAsync(callback?: (result: AsyncResult<number>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o número de índice mais alto na coleção de tarefas do projeto atual.

Retornos

void

Exemplos

// 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";
    const 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').on("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() {
        const 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) {
        const defer = $.Deferred();
        for (let 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)

Somente documentos do projeto. Obter o campo Project (por exemplo, ProjectWebAccessURL).

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

Parâmetros

fieldId

number

Campos de nível de projeto.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém a fieldValue propriedade, que representa o valor do campo especificado.

Retornos

void

getProjectFieldAsync(fieldId, callback)

Somente documentos do projeto. Obter o campo Project (por exemplo, ProjectWebAccessURL).

getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult<any>) => void): void;

Parâmetros

fieldId

number

Campos de nível de projeto.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém a fieldValue propriedade, que representa o valor do campo especificado.

Retornos

void

Exemplos

// 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() {
        const fields =
            [Office.ProjectProjectFields.Start, 
             Office.ProjectProjectFields.Finish, 
             Office.ProjectProjectFields.GUID];
        const fieldValues = ['Start: ', 'Finish: ', 'GUID: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == fields.length) {
                let output = '';
                for (let 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)

Somente documentos do projeto. Obtenha o GUID do recurso que tem o índice especificado na coleção de recursos.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

resourceIndex

number

O índice do recurso na coleção de recursos do projeto.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

getResourceByIndexAsync(resourceIndex, callback)

Somente documentos do projeto. Obtenha o GUID do recurso que tem o índice especificado na coleção de recursos.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult<string>) => void): void;

Parâmetros

resourceIndex

number

O índice do recurso na coleção de recursos do projeto.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

Exemplos

// 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";
    const 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').on("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() {
        const 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) {
        const defer = $.Deferred();
        for (let 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)

Somente documentos do projeto. Obtenha o campo de recursos para a ID do recurso fornecida. (por exemplo, ResourceName)

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

Parâmetros

resourceId

string

Uma cadeia de caracteres ou um valor da ID do recurso.

fieldId

number

Campos de Recursos.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

getResourceFieldAsync(resourceId, fieldId, callback)

Somente documentos do projeto. Obtenha o campo de recursos para a ID do recurso fornecida. (por exemplo, ResourceName)

getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult<string>) => void): void;

Parâmetros

resourceId

string

Uma cadeia de caracteres ou um valor da ID do recurso.

fieldId

number

Campos de Recursos.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

Exemplos

// 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').on("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() {
        const 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) {
        const targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        const fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                let output = '';
                for (let 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)

Lê os dados contidos na seleção atual no documento.

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

Parâmetros

coercionType
Office.CoercionType

O tipo de estrutura de dados a ser retornada. Consulte a seção Comentários para os tipos de coerção com suporte de cada aplicativo.

options
Office.GetSelectedDataOptions

Fornece opções para personalizar quais dados são retornados e como eles são formatados.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado são os dados na seleção atual. Isso é retornado na estrutura de dados ou no formato especificado com o parâmetro coercionType. (Consulte Comentários para obter mais informações sobre a coerção de dados.)

Retornos

void

Comentários

Conjuntos de requisitos:

Na função de retorno de chamada que é passada para o método getSelectedDataAsync, você pode usar as propriedades do objeto AsyncResult para retornar as informações a seguir.

Propriedade Usar
AsyncResult.value Sempre retorna undefined porque não há nenhum objeto ou dados para recuperar.
AsyncResult.status Determinar o sucesso ou falha da operação.
AsyncResult.error Acessar um objeto Error que fornecerá informações de erro se a operação tiver falhado.
AsyncResult.asyncContext Defina um item de qualquer tipo retornado no objeto AsyncResult sem ser alterado.

Os valores possíveis para o parâmetro Office.CoercionType variam de acordo com o aplicativo do Office.

CoercionType Aplicativos com suporte
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrizes)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (Objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadeia de caracteres)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel no Windows e no Mac

Exemplos

// 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.

// Displays the user's current selection.
function showSelection() {
    Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        {
            valueFormat: Office.ValueFormat.Unformatted,
            filterType: Office.FilterType.All
        },
        (result) => {
            const 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: Office.ValueFormat.Unformatted,
            filterType: Office.FilterType.All
        },
        (asyncResult) => {
            const error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                write(error.name + ": " + error.message);
            } 
            else {
                // Get selected data.
                const 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>

// The onReady function must be run each time a new page is loaded.
Office.onReady(() => {
    $(document).ready(() => {
        // After the DOM is loaded, add-in-specific code can run.
        $('#get-info').on("click", getSelectedText);
    });
});

// Gets the text from the selected cells in the document, and displays it in the add-in.
function getSelectedText() {
    Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        { asyncContext: "Some related info" },
        (result) => {
            if (result.status === Office.AsyncResultStatus.Failed) {
                onError(result.error);
            }
            else {
                const 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);
}

getSelectedDataAsync(coercionType, callback)

Lê os dados contidos na seleção atual no documento.

getSelectedDataAsync<T>(coercionType: Office.CoercionType, callback?: (result: AsyncResult<T>) => void): void;

Parâmetros

coercionType
Office.CoercionType

O tipo de estrutura de dados a ser retornada. Consulte a seção Comentários para os tipos de coerção com suporte de cada aplicativo.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado são os dados na seleção atual. Isso é retornado na estrutura de dados ou no formato especificado com o parâmetro coercionType. (Consulte Comentários para obter mais informações sobre a coerção de dados.)

Retornos

void

Comentários

Conjuntos de requisitos:

Na função de retorno de chamada que é passada para o método getSelectedDataAsync, você pode usar as propriedades do objeto AsyncResult para retornar as informações a seguir.

Propriedade Usar
AsyncResult.value Sempre retorna undefined porque não há nenhum objeto ou dados para recuperar.
AsyncResult.status Determinar o sucesso ou falha da operação.
AsyncResult.error Acessar um objeto Error que fornecerá informações de erro se a operação tiver falhado.
AsyncResult.asyncContext Defina um item de qualquer tipo retornado no objeto AsyncResult sem ser alterado.

Os valores possíveis para o parâmetro Office.CoercionType variam de acordo com o aplicativo do Office.

CoercionType Aplicativos com suporte
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrizes)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (Objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadeia de caracteres)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel no Windows e no Mac

getSelectedResourceAsync(options, callback)

Somente documentos do projeto. Obtenha a ID do recurso selecionado atualmente.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

getSelectedResourceAsync(callback)

Somente documentos do projeto. Obtenha a ID do recurso selecionado atualmente.

getSelectedResourceAsync(callback?: (result: AsyncResult<string>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

Exemplos

// 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').on("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() {
        const 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) {
        const targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        const fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                let output = '';
                for (let 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)

Somente documentos do projeto. Obtenha a ID da Tarefa selecionada atualmente.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

getSelectedTaskAsync(callback)

Somente documentos do projeto. Obtenha a ID da Tarefa selecionada atualmente.

getSelectedTaskAsync(callback?: (result: AsyncResult<string>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID do recurso como uma cadeia de caracteres.

Retornos

void

Exemplos

// 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').on("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() {
        const 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 {
                    const taskInfo = result.value;
                    const 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)

Somente documentos do projeto. Obtenha o tipo de exibição selecionado atual (por exemplo, Gantt) e o Nome de Exibição.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: viewName - O nome da exibição, como uma constante ProjectViewTypes. viewType - O tipo de exibição, como o valor inteiro de uma constante ProjectViewTypes.

Retornos

void

getSelectedViewAsync(callback)

Somente documentos do projeto. Obtenha o tipo de exibição selecionado atual (por exemplo, Gantt) e o Nome de Exibição.

getSelectedViewAsync(callback?: (result: AsyncResult<any>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: viewName - O nome da exibição, como uma constante ProjectViewTypes. viewType - O tipo de exibição, como o valor inteiro de uma constante ProjectViewTypes.

Retornos

void

Exemplos

// 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 {
                    const 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)

Somente documentos do projeto. Obtenha o Nome da Tarefa, A ID da Tarefa WSS e ResourceNames para determinado taskId.

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

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da Tarefa.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: taskName – O nome da tarefa. wssTaskId - A ID da tarefa na lista de tarefas sincronizadas do SharePoint. Se o projeto não estiver sincronizado com uma lista de tarefas do SharePoint, o valor será 0. resourceNames - A lista separada por vírgulas dos nomes dos recursos atribuídos à tarefa.

Retornos

void

getTaskAsync(taskId, callback)

Somente documentos do projeto. Obtenha o Nome da Tarefa, A ID da Tarefa WSS e ResourceNames para determinado taskId.

getTaskAsync(taskId: string, callback?: (result: AsyncResult<any>) => void): void;

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da Tarefa.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: taskName – O nome da tarefa. wssTaskId - A ID da tarefa na lista de tarefas sincronizadas do SharePoint. Se o projeto não estiver sincronizado com uma lista de tarefas do SharePoint, o valor será 0. resourceNames - A lista separada por vírgulas dos nomes dos recursos atribuídos à tarefa.

Retornos

void

Exemplos

// 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').on("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() {
        const 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 {
                    const taskInfo = result.value;
                    const 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)

Somente documentos do projeto. Obtenha o GUID da tarefa que tem o índice especificado na coleção de tarefas.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

taskIndex

number

O índice da tarefa no conjunto de tarefas do projeto.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID da tarefa como uma cadeia de caracteres.

Retornos

void

getTaskByIndexAsync(taskIndex, callback)

Somente documentos do projeto. Obtenha o GUID da tarefa que tem o índice especificado na coleção de tarefas.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult<string>) => void): void;

Parâmetros

taskIndex

number

O índice da tarefa no conjunto de tarefas do projeto.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é o GUID da tarefa como uma cadeia de caracteres.

Retornos

void

Exemplos

// 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";
    const 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').on("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() {
        const 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) {
        const defer = $.Deferred();
        for (let 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)

Somente documentos do projeto. Obtenha o campo de tarefas para a ID da tarefa fornecida. (por exemplo, StartDate).

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

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da Tarefa.

fieldId

number

Campos de Tarefas.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém a fieldValue propriedade, que representa o valor do campo especificado.

Retornos

void

getTaskFieldAsync(taskId, fieldId, callback)

Somente documentos do projeto. Obtenha o campo de tarefas para a ID da tarefa fornecida. (por exemplo, StartDate).

getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult<any>) => void): void;

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da Tarefa.

fieldId

number

Campos de Tarefas.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém a fieldValue propriedade, que representa o valor do campo especificado.

Retornos

void

Exemplos

// 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').on("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() {
        const 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) {
        let output = '';
        const targetFields = [Office.ProjectTaskFields.Priority, Office.ProjectTaskFields.PercentComplete];
        const fieldValues = ['Priority: ', '% Complete: '];
        let index = 0;
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                for (let 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)

Somente documentos do projeto. Obtenha a URL do WSS e o nome da lista para a Lista de Tarefas, o MPP também está sincronizado.

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

Parâmetros

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: listName - o nome da lista de tarefas sincronizada do SharePoint. serverUrl - a URL da lista de tarefas sincronizada do SharePoint.

Retornos

void

getWSSUrlAsync(callback)

Somente documentos do projeto. Obtenha a URL do WSS e o nome da lista para a Lista de Tarefas, o MPP também está sincronizado.

getWSSUrlAsync(callback?: (result: AsyncResult<any>) => void): void;

Parâmetros

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado contém as seguintes propriedades: listName - o nome da lista de tarefas sincronizada do SharePoint. serverUrl - a URL da lista de tarefas sincronizada do SharePoint.

Retornos

void

goToByIdAsync(id, goToType, options, callback)

Vai para o objeto ou local especificado no documento.

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

Parâmetros

id

string | number

O identificador do objeto ou local para o qual ir.

goToType
Office.GoToType

O tipo de local para o qual ir.

options
Office.GoToByIdOptions

Fornece opções para selecionar o local para o qual é navegado.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é a exibição atual.

Retornos

void

Comentários

Conjunto de requisitos: não em um conjunto

O PowerPoint não dá suporte ao método goToByIdAsync em Modos de Exibição Mestre.

O comportamento causado pela opção selectionMode varia de acordo com o aplicativo do Office:

No Excel: Office.SelectionMode.Selected seleciona todo o conteúdo na associação ou no item nomeado. Office.SelectionMode.None para associações de texto, seleciona a célula, para associações, de matriz, associações de tabela e itens nomeados, seleciona a primeira célula de dados (não a primeira célula na linha de cabeçalho para tabelas).

No PowerPoint: Office.SelectionMode.Selected seleciona o título do slide ou a primeira caixa de texto no slide. Office.SelectionMode.None não seleciona nada.

Em Word: Office.SelectionMode.Selected seleciona todo o conteúdo na associação. Office.SelectionMode.None para associações de texto, move o cursor para o início do texto, para associações de matriz e associações de tabela, seleciona a primeira célula de dados (não a primeira célula na linha de cabeçalho para tabelas).

goToByIdAsync(id, goToType, callback)

Vai para o objeto ou local especificado no documento.

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

Parâmetros

id

string | number

O identificador do objeto ou local para o qual ir.

goToType
Office.GoToType

O tipo de local para o qual ir.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A value propriedade do resultado é a exibição atual.

Retornos

void

Comentários

Conjunto de requisitos: não em um conjunto

O PowerPoint não dá suporte ao método goToByIdAsync em Modos de Exibição Mestre.

O comportamento causado pela opção selectionMode varia de acordo com o aplicativo do Office:

No Excel: Office.SelectionMode.Selected seleciona todo o conteúdo na associação ou no item nomeado. Office.SelectionMode.None para associações de texto, seleciona a célula, para associações, de matriz, associações de tabela e itens nomeados, seleciona a primeira célula de dados (não a primeira célula na linha de cabeçalho para tabelas).

No PowerPoint: Office.SelectionMode.Selected seleciona o título do slide ou a primeira caixa de texto no slide. Office.SelectionMode.None não seleciona nada.

Em Word: Office.SelectionMode.Selected seleciona todo o conteúdo na associação. Office.SelectionMode.None para associações de texto, move o cursor para o início do texto, para associações de matriz e associações de tabela, seleciona a primeira célula de dados (não a primeira célula na linha de cabeçalho para tabelas).

Exemplos

// 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.
let 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() {
    const goToFirst = Office.Index.First;
    const goToLast = Office.Index.Last;
    const goToPrevious = Office.Index.Previous;
    const 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)

Remove um manipulador de eventos para o tipo de evento especificado.

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

Parâmetros

eventType
Office.EventType

O tipo de evento. O documento pode ser 'Document.SelectionChanged' ou 'Document.ActiveViewChanged'.

options
Office.RemoveHandlerOptions

Fornece opções para determinar quais manipuladores ou manipuladores de eventos são removidos.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Comentários

Conjunto de requisitos: DocumentEvents

removeHandlerAsync(eventType, callback)

Remove um manipulador de eventos para o tipo de evento especificado.

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

Parâmetros

eventType
Office.EventType

O tipo de evento. O documento pode ser 'Document.SelectionChanged' ou 'Document.ActiveViewChanged'.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Comentários

Conjunto de requisitos: DocumentEvents

Exemplos

// 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').on("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)

Somente documentos do projeto. Defina o campo de recursos para a ID de recurso especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

resourceId

string

Uma cadeia de caracteres ou um valor da ID do recurso.

fieldId

number

Campos de Recursos.

fieldValue

string | number | boolean | object

Valor do campo de destino.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Somente documentos do projeto. Defina o campo de recursos para a ID de recurso especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

resourceId

string

Uma cadeia de caracteres ou um valor da ID do recurso.

fieldId

number

Campos de Recursos.

fieldValue

string | number | boolean | object

Valor do campo de destino.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Exemplos

// 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').on("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() {
        const 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) {
        const targetFields = [Office.ProjectResourceFields.StandardRate, Office.ProjectResourceFields.Notes];
        const fieldValues = [.28, 'Notes for the resource.'];

        // Set the field value. If the call is successful, set the next field.
        for (let 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)

Grava os dados especificados na seleção atual.

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

Parâmetros

data

string | Office.TableData | any[][]

Os dados a serem definidos. Um valor de cadeia de caracteres ou Office.CoercionType , matriz 2D ou objeto TableData.

Se o valor passado for data :

  • Uma cadeia de caracteres: será inserido um texto sem formatação ou qualquer coisa que possa ser forçada para uma string. No Excel, você também pode especificar dados como uma fórmula válida para adicionar essa fórmula à célula selecionada. Por exemplo, definir dados como "=SUM(A1:A5)" totalizará os valores no intervalo especificado. No entanto, após definir uma fórmula na célula associada, não é possível ler a fórmula adicionada (ou qualquer fórmula preexistente) da célula associada. Se você chamar o método Document.getSelectedDataAsync na célula associada para ler seus dados, o método poderá retornar apenas os dados exibidos na célula (o resultado da fórmula).

  • Uma matriz de matrizes ("matrix"): Serão inseridos dados tabulares sem cabeçalhos. Por exemplo, para gravar dados em três linhas em duas colunas, você pode passar uma matriz como esta: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. Para gravar uma única coluna de três linhas, passe uma matriz como esta: [["R1C1"], ["R2C1"], ["R3C1"]]

No Excel, você também pode especificar dados como uma matriz de matrizes que contém fórmulas válidas para adicioná-los às células selecionadas. Por exemplo, se nenhum outro dado for substituído, definir dados como [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] adicionará essas duas fórmulas à seleção. Assim como ao definir uma fórmula em uma única célula como "texto", não é possível ler as fórmulas adicionadas (ou qualquer fórmula preexistente) após elas terem sido configuradas; você poderá ler apenas resultados de fórmulas.

  • Um objeto TableData: será inserida uma tabela com cabeçalhos. No Excel, se você especificar fórmulas no objeto TableData que você passa para o parâmetro de dados, talvez não obtenha os resultados esperados devido ao recurso "colunas calculadas" do Excel, que duplica automaticamente fórmulas em uma coluna. Para contornar isso quando quiser escrever data que contém fórmulas em uma tabela selecionada, tente especificar os dados como uma matriz de matrizes (em vez de um objeto TableData) e especifique o coercionType como Microsoft.Office.Matrix ou "matrix". No entanto, essa técnica bloqueará o recurso "colunas calculadas" somente quando uma das seguintes condições for atendida: (1) você está escrevendo para todas as células da coluna ou (2) já há pelo menos duas fórmulas diferentes na coluna.
options
Office.SetSelectedDataOptions

Fornece opções de como inserir dados na seleção.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A propriedade AsyncResult.value sempre retorna undefined porque não há nenhum objeto ou dados a serem recuperados.

Retornos

void

Comentários

Conjuntos de requisitos:

Comportamentos específicos do aplicativo

As ações específicas do aplicativo a seguir se aplicam ao gravar dados em uma seleção.

Application Condition Comportamento
Word Se não houver seleção e o ponto de inserção estiver em um local válido, o especificado data será inserido no ponto de inserção Se data for uma cadeia de caracteres, o texto especificado será inserido.
Se data for uma matriz de matrizes ("matriz") ou um objeto TableData, uma nova tabela Word será inserida.
Se os dados forem HTML, o HTML especificado será inserido. (**Importante**: se qualquer um dos HTML inseridos for inválido, Word não gerará um erro. Word inserirá o máximo de HTML possível e omite todos os dados inválidos).
Se data for O XML do Office Open, o XML especificado será inserido.
Se data for um fluxo de imagem codificado por Base64, a imagem especificada será inserida.
Se houver uma seleção Ele será substituído pelo especificado data seguindo as mesmas regras acima.
Inserir imagens As imagens inseridas são colocadas embutidas. Os parâmetros imageLeft e imageTop são ignorados. A taxa de proporção da imagem sempre está bloqueada. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.
Excel Se uma única célula for selecionada Se data for uma cadeia de caracteres, o texto especificado será inserido como o valor da célula atual.
Se data for uma matriz de matrizes ("matriz"), o conjunto especificado de linhas e colunas será inserido, se nenhum outro dado nas células ao redor for substituído.
Se data for um objeto TableData, uma nova tabela do Excel com o conjunto especificado de linhas e cabeçalhos será inserida, se nenhum outro dado nas células ao redor for substituído.
Se várias células forem selecionadas Se a forma não corresponder à forma de data, um erro será retornado.
Se a forma da seleção corresponder exatamente à forma de data, os valores das células selecionadas serão atualizados com base nos valores em data.
Inserir imagens As imagens inseridas são flutuantes. A imagem de posiçãoLeft e os parâmetros imageTop são relativos às células selecionadas no momento. Valores negativos de imageLeft e imageTop são permitidos e podem ser reajustados pelo Excel para posicionar a imagem dentro de uma planilha. A taxa de proporção da imagem fica bloqueada, a menos que ambos os parâmetros imageWidth e imageHeight sejam fornecidos. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.
Todos os outros casos Um erro é retornado.
Excel Online Além dos comportamentos descritos para o Excel acima, esses limites se aplicam ao gravar dados no Excel na Web O número total de células que você pode gravar em uma planilha com o data parâmetro não pode exceder 20.000 em uma única chamada para esse método.
O número de grupos de formatação passados para o cellFormat parâmetro não pode exceder 100. Um único grupo formatação consiste em um conjunto de formatação aplicado a um intervalo de células especificado.
PowerPoint Inserir imagem As imagens inseridas são flutuantes. Os parâmetros imageLeft e imageTop são opcionais, mas, se fornecidos, ambos devem estar presentes. Se um único valor for fornecido, ele será ignorado. Valores negativos de imageLeft e imageTop são permitidos e podem posicionar uma imagem fora de um slide. Se nenhum parâmetro opcional for fornecido e o slide tiver um espaço reservado, a imagem substituirá o espaço reservado no slide. A taxa de proporção da imagem ficará bloqueada, a menos que ambos os parâmetros imageWidth e imageHeight sejam fornecidos. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.

Aplicativos

Os valores possíveis para o parâmetro Office.CoercionType variam de acordo com o aplicativo do Office.

CoercionType Aplicativos com suporte
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrizes)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint na Web e no Windows
Office.CoercionType.Table (Objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadeia de caracteres)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel no Windows e no Mac
  • PowerPoint na Web, no Windows e no Mac
  • Word no Windows e no Mac

Exemplos

// 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) {
            const 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) {
            const 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.
    const 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) {
            const 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);
        }
    });
}

// In Word, PowerPoint, or Excel, if you want to write an scalable vector graphic (SVG) to the selection, you can specify the 
// coercionType parameter as `XmlSvg` as shown in the following example. Note that imageLeft and imageTop are ignored by Word.
function insertSvgAtSelection(base64EncodedImageStr) {
    Office.context.document.setSelectedDataAsync(getImageAsBase64String(), {
        coercionType: Office.CoercionType.XmlSvg,
        imageLeft: 50,
        imageTop: 50,
        imageWidth: 400
    },
        function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                console.log(asyncResult.error.message);
            }
        });
}

setSelectedDataAsync(data, callback)

Grava os dados especificados na seleção atual.

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

Parâmetros

data

string | Office.TableData | any[][]

Os dados a serem definidos. Um valor de cadeia de caracteres ou Office.CoercionType , matriz 2D ou objeto TableData.

Se o valor passado for data :

  • Uma cadeia de caracteres: será inserido um texto sem formatação ou qualquer coisa que possa ser forçada para uma string. No Excel, você também pode especificar dados como uma fórmula válida para adicionar essa fórmula à célula selecionada. Por exemplo, definir dados como "=SUM(A1:A5)" totalizará os valores no intervalo especificado. No entanto, após definir uma fórmula na célula associada, não é possível ler a fórmula adicionada (ou qualquer fórmula preexistente) da célula associada. Se você chamar o método Document.getSelectedDataAsync na célula associada para ler seus dados, o método poderá retornar apenas os dados exibidos na célula (o resultado da fórmula).

  • Uma matriz de matrizes ("matrix"): Serão inseridos dados tabulares sem cabeçalhos. Por exemplo, para gravar dados em três linhas em duas colunas, você pode passar uma matriz como esta: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. Para gravar uma única coluna de três linhas, passe uma matriz como esta: [["R1C1"], ["R2C1"], ["R3C1"]]

No Excel, você também pode especificar dados como uma matriz de matrizes que contém fórmulas válidas para adicioná-los às células selecionadas. Por exemplo, se nenhum outro dado for substituído, definir dados como [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] adicionará essas duas fórmulas à seleção. Assim como ao definir uma fórmula em uma única célula como "texto", não é possível ler as fórmulas adicionadas (ou qualquer fórmula preexistente) após elas terem sido configuradas; você poderá ler apenas resultados de fórmulas.

  • Um objeto TableData: será inserida uma tabela com cabeçalhos. No Excel, se você especificar fórmulas no objeto TableData que você passa para o parâmetro de dados, talvez não obtenha os resultados esperados devido ao recurso "colunas calculadas" do Excel, que duplica automaticamente fórmulas em uma coluna. Para contornar isso quando quiser escrever data que contém fórmulas em uma tabela selecionada, tente especificar os dados como uma matriz de matrizes (em vez de um objeto TableData) e especifique o coercionType como Microsoft.Office.Matrix ou "matrix". No entanto, essa técnica bloqueará o recurso "colunas calculadas" somente quando uma das seguintes condições for atendida: (1) você está escrevendo para todas as células da coluna ou (2) já há pelo menos duas fórmulas diferentes na coluna.
callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult. A propriedade AsyncResult.value sempre retorna undefined porque não há nenhum objeto ou dados a serem recuperados.

Retornos

void

Comentários

Conjuntos de requisitos:

Comportamentos específicos do aplicativo

As ações específicas do aplicativo a seguir se aplicam ao gravar dados em uma seleção.

Application Condition Comportamento
Word Se não houver seleção e o ponto de inserção estiver em um local válido, os 'dados' especificados serão inseridos no ponto de inserção Se data for uma cadeia de caracteres, o texto especificado será inserido.
Se data for uma matriz de matrizes ("matriz") ou um objeto TableData, uma nova tabela Word será inserida.
Se data for HTML, o HTML especificado será inserido. (**Importante**: se qualquer um dos HTML inseridos for inválido, Word não gerará um erro. Word inserirá o máximo de HTML possível e omite todos os dados inválidos).
Se data for O XML do Office Open, o XML especificado será inserido.
Se data for um fluxo de imagem codificado por Base64, a imagem especificada será inserida.
Se houver uma seleção Ele será substituído pelo especificado data seguindo as mesmas regras acima.
Inserir imagens As imagens inseridas são colocadas embutidas. Os parâmetros imageLeft e imageTop são ignorados. A taxa de proporção da imagem sempre está bloqueada. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.
Excel Se uma única célula for selecionada Se data for uma cadeia de caracteres, o texto especificado será inserido como o valor da célula atual.
Se data for uma matriz de matrizes ("matriz"), o conjunto especificado de linhas e colunas será inserido, se nenhum outro dado nas células ao redor for substituído.
Se data for um objeto TableData, uma nova tabela do Excel com o conjunto especificado de linhas e cabeçalhos será inserida, se nenhum outro dado nas células ao redor for substituído.
Se várias células forem selecionadas Se a forma não corresponder à forma de data, um erro será retornado.
Se a forma da seleção corresponder exatamente à forma de data, os valores das células selecionadas serão atualizados com base nos valores em data.
Inserir imagens As imagens inseridas são flutuantes. A imagem de posiçãoLeft e os parâmetros imageTop são relativos às células selecionadas no momento. Valores negativos de imageLeft e imageTop são permitidos e podem ser reajustados pelo Excel para posicionar a imagem dentro de uma planilha. A taxa de proporção da imagem fica bloqueada, a menos que ambos os parâmetros imageWidth e imageHeight sejam fornecidos. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.
Todos os outros casos Um erro é retornado.
Excel Online Além dos comportamentos descritos para o Excel acima, esses limites se aplicam ao gravar dados no Excel na Web O número total de células que você pode gravar em uma planilha com o data parâmetro não pode exceder 20.000 em uma única chamada para esse método.
O número de grupos de formatação passados para o cellFormat parâmetro não pode exceder 100. Um único grupo formatação consiste em um conjunto de formatação aplicado a um intervalo de células especificado.
PowerPoint Inserir imagem As imagens inseridas são flutuantes. Os parâmetros imageLeft e imageTop são opcionais, mas, se fornecidos, ambos devem estar presentes. Se um único valor for fornecido, ele será ignorado. Valores negativos de imageLeft e imageTop são permitidos e podem posicionar uma imagem fora de um slide. Se nenhum parâmetro opcional for fornecido e o slide tiver um espaço reservado, a imagem substituirá o espaço reservado no slide. A taxa de proporção da imagem ficará bloqueada, a menos que ambos os parâmetros imageWidth e imageHeight sejam fornecidos. Se apenas um dos parâmetros imageWidth e imageHeight for fornecido, o outro valor será automaticamente dimensionado para manter a taxa de proporção original.

Aplicativos

Os valores possíveis para o parâmetro Office.CoercionType variam de acordo com o aplicativo do Office.

CoercionType Aplicativos com suporte
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrizes)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint na Web e no Windows
Office.CoercionType.Table (Objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadeia de caracteres)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel no Windows e no Mac
  • PowerPoint na Web, no Windows e no Mac
  • Word no Windows e no Mac

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

Somente documentos do projeto. Defina o campo de tarefas para a ID da tarefa especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da tarefa.

fieldId

number

Campos de Tarefas.

fieldValue

string | number | boolean | object

Valor do campo de destino.

options
Office.AsyncContextOptions

Fornece uma opção para preservar dados de contexto de qualquer tipo, inalterados, para uso em um retorno de chamada.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Somente documentos do projeto. Defina o campo de tarefas para a ID da tarefa especificada.

Importante: essa API funciona apenas no Project na área de trabalho do Windows.

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

Parâmetros

taskId

string

Uma cadeia de caracteres ou um valor da ID da Tarefa.

fieldId

number

Campos de Tarefas.

fieldValue

string | number | boolean | object

Valor do campo de destino.

callback

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

Opcional. Uma função que é invocada quando o retorno de chamada retorna, cujo único parâmetro é do tipo Office.AsyncResult.

Retornos

void

Exemplos

// 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').on("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() {
        const 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) {
        const targetFields = [Office.ProjectTaskFields.Active, Office.ProjectTaskFields.Notes];
        const fieldValues = [true, 'Notes for the task.'];

        // Set the field value. If the call is successful, set the next field.
        for (let 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);
    }
})();