Office.Document interface

Una clase abstracta que representa el documento con el que interactúa el complemento.

Comentarios

Aplicaciones: Excel, PowerPoint, Project, Word

Ejemplos

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

Propiedades

bindings

Obtiene un objeto que proporciona acceso a los enlaces que se han definido en el documento.

customXmlParts

Obtiene un objeto que representa los elementos XML personalizados del documento.

mode

Obtiene el modo en el que se encuentra el documento.

settings

Obtiene un objeto que representa la configuración personalizada que se ha guardado del complemento de contenido o del panel de tareas para el documento actual.

url

Obtiene la dirección URL del documento que la aplicación de Office tiene abierta actualmente. Devuelve null si la dirección URL no está disponible.

Métodos

addHandlerAsync(eventType, handler, options, callback)

Agrega un controlador de eventos para un evento de objeto Document.

addHandlerAsync(eventType, handler, callback)

Agrega un controlador de eventos para un evento de objeto Document.

getActiveViewAsync(options, callback)

Devuelve el estado de la vista actual de la presentación (edición o lectura).

getActiveViewAsync(callback)

Devuelve el estado de la vista actual de la presentación (edición o lectura).

getFileAsync(fileType, options, callback)

Devuelve el archivo de documento entero en segmentos de hasta 4194304 bytes (4 MB). Para los complementos en iPad, el segmento de archivos se admite hasta 65536 (64 KB). Tenga en cuenta que, si especifica un tamaño del segmento del archivo superior al límite permitido, se producirá el error "Error interno".

getFileAsync(fileType, callback)

Devuelve el archivo de documento entero en segmentos de hasta 4194304 bytes (4 MB). Para los complementos en iPad, el segmento de archivos se admite hasta 65536 (64 KB). Tenga en cuenta que, si especifica un tamaño del segmento del archivo superior al límite permitido, se producirá el error "Error interno".

getFilePropertiesAsync(options, callback)

Obtiene las propiedades de archivo del documento actual.

getFilePropertiesAsync(callback)

Obtiene las propiedades de archivo del documento actual.

getMaxResourceIndexAsync(options, callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de recursos del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getMaxResourceIndexAsync(callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de recursos del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getMaxTaskIndexAsync(options, callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de tareas del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getMaxTaskIndexAsync(callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de tareas del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getProjectFieldAsync(fieldId, options, callback)

Solo documentos de proyecto. Obtener campo Proyecto (por ejemplo, ProjectWebAccessURL).

getProjectFieldAsync(fieldId, callback)

Solo documentos de proyecto. Obtener campo Proyecto (por ejemplo, ProjectWebAccessURL).

getResourceByIndexAsync(resourceIndex, options, callback)

Solo documentos de proyecto. Obtenga el GUID del recurso que tiene el índice especificado en la colección de recursos.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getResourceByIndexAsync(resourceIndex, callback)

Solo documentos de proyecto. Obtenga el GUID del recurso que tiene el índice especificado en la colección de recursos.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getResourceFieldAsync(resourceId, fieldId, options, callback)

Solo documentos de proyecto. Obtenga el campo de recurso para el identificador de recurso proporcionado. (por ejemplo, ResourceName)

getResourceFieldAsync(resourceId, fieldId, callback)

Solo documentos de proyecto. Obtenga el campo de recurso para el identificador de recurso proporcionado. (por ejemplo, ResourceName)

getSelectedDataAsync(coercionType, options, callback)

Lee los datos incluidos en la selección actual del documento.

getSelectedDataAsync(coercionType, callback)

Lee los datos incluidos en la selección actual del documento.

getSelectedResourceAsync(options, callback)

Solo documentos de proyecto. Obtenga el identificador del recurso seleccionado actual.

getSelectedResourceAsync(callback)

Solo documentos de proyecto. Obtenga el identificador del recurso seleccionado actual.

getSelectedTaskAsync(options, callback)

Solo documentos de proyecto. Obtenga el identificador de tarea seleccionado actual.

getSelectedTaskAsync(callback)

Solo documentos de proyecto. Obtenga el identificador de tarea seleccionado actual.

getSelectedViewAsync(options, callback)

Solo documentos de proyecto. Obtenga el tipo de vista seleccionado actual (por ejemplo, Gantt) y el nombre de la vista.

getSelectedViewAsync(callback)

Solo documentos de proyecto. Obtenga el tipo de vista seleccionado actual (por ejemplo, Gantt) y el nombre de la vista.

getTaskAsync(taskId, options, callback)

Solo documentos de proyecto. Obtenga el nombre de la tarea, el identificador de tarea de WSS y los nombres de recurso para un taskId determinado.

getTaskAsync(taskId, callback)

Solo documentos de proyecto. Obtenga el nombre de la tarea, el identificador de tarea de WSS y los nombres de recurso para un taskId determinado.

getTaskByIndexAsync(taskIndex, options, callback)

Solo documentos de proyecto. Obtenga el GUID de la tarea que tiene el índice especificado en la colección de tareas.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getTaskByIndexAsync(taskIndex, callback)

Solo documentos de proyecto. Obtenga el GUID de la tarea que tiene el índice especificado en la colección de tareas.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

getTaskFieldAsync(taskId, fieldId, options, callback)

Solo documentos de proyecto. Obtenga el campo de tarea para el identificador de tarea proporcionado. (por ejemplo, StartDate).

getTaskFieldAsync(taskId, fieldId, callback)

Solo documentos de proyecto. Obtenga el campo de tarea para el identificador de tarea proporcionado. (por ejemplo, StartDate).

getWSSUrlAsync(options, callback)

Solo documentos de proyecto. Obtenga la dirección URL de WSS y el nombre de la lista de tareas, el MPP también se sincroniza.

getWSSUrlAsync(callback)

Solo documentos de proyecto. Obtenga la dirección URL de WSS y el nombre de la lista de tareas, el MPP también se sincroniza.

goToByIdAsync(id, goToType, options, callback)

Va al objeto o la ubicación que se haya especificado en el documento.

goToByIdAsync(id, goToType, callback)

Va al objeto o la ubicación que se haya especificado en el documento.

removeHandlerAsync(eventType, options, callback)

Quita un controlador de eventos para el tipo de evento especificado.

removeHandlerAsync(eventType, callback)

Quita un controlador de eventos para el tipo de evento especificado.

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

Solo documentos de proyecto. Establezca el campo de recurso para el identificador de recurso especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Solo documentos de proyecto. Establezca el campo de recurso para el identificador de recurso especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

setSelectedDataAsync(data, options, callback)

Escribe los datos especificados en la selección actual.

setSelectedDataAsync(data, callback)

Escribe los datos especificados en la selección actual.

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

Solo documentos de proyecto. Establezca el campo de tarea para el identificador de tarea especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Solo documentos de proyecto. Establezca el campo de tarea para el identificador de tarea especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

Detalles de las propiedades

bindings

Obtiene un objeto que proporciona acceso a los enlaces que se han definido en el documento.

bindings: Bindings;

Valor de propiedad

Comentarios

No crea una instancia del objeto Document directamente en el script. Si desea llamar a miembros del objeto Document para que interactúen con la hoja de cálculo o el documento actual, use Office.context.document en el script.

Ejemplos

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

Obtiene un objeto que representa los elementos XML personalizados del documento.

customXmlParts: CustomXmlParts;

Valor de propiedad

Ejemplos

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

Obtiene el modo en el que se encuentra el documento.

mode: DocumentMode;

Valor de propiedad

Ejemplos

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

Obtiene un objeto que representa la configuración personalizada que se ha guardado del complemento de contenido o del panel de tareas para el documento actual.

settings: Settings;

Valor de propiedad

url

Obtiene la dirección URL del documento que la aplicación de Office tiene abierta actualmente. Devuelve null si la dirección URL no está disponible.

url: string;

Valor de propiedad

string

Ejemplos

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

Detalles del método

addHandlerAsync(eventType, handler, options, callback)

Agrega un controlador de eventos para un 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 un evento de objeto Document, el parámetro eventType se puede especificar como Office.EventType.Document.SelectionChanged o Office.EventType.Document.ActiveViewChanged, o el valor de texto correspondiente de esta enumeración.

handler

any

Función de controlador de eventos que se va a agregar, cuyo único parámetro es de tipo Office.DocumentSelectionChangedEventArgs. Obligatorio.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Comentarios

Conjunto de requisitos: DocumentEvents

Puede agregar varios controladores de eventos para el eventType especificado siempre y cuando el nombre de cada función de controlador de eventos sea único.

addHandlerAsync(eventType, handler, callback)

Agrega un controlador de eventos para un evento de objeto Document.

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

Parámetros

eventType
Office.EventType

Para un evento de objeto Document, el parámetro eventType se puede especificar como Office.EventType.Document.SelectionChanged o Office.EventType.Document.ActiveViewChanged, o el valor de texto correspondiente de esta enumeración.

handler

any

Función de controlador de eventos que se va a agregar, cuyo único parámetro es de tipo Office.DocumentSelectionChangedEventArgs. Obligatorio.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Comentarios

Conjunto de requisitos: DocumentEvents

Puede agregar varios controladores de eventos para el eventType especificado siempre y cuando el nombre de cada función de controlador de eventos sea único.

Ejemplos

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

Devuelve el estado de la vista actual de la presentación (edición o lectura).

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el estado de la vista actual de la presentación. El valor devuelto puede ser "edit" o "read". "editar" corresponde a cualquiera de las vistas en las que se pueden editar diapositivas: Normal, Clasificador de diapositivas o Vista de esquema. "lectura" corresponde a presentación con diapositivas o vista de lectura.

Devoluciones

void

Comentarios

Conjunto de requisitos: ActiveView

Puede desencadenar un evento al cambiar la vista.

getActiveViewAsync(callback)

Devuelve el estado de la vista actual de la presentación (edición o lectura).

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el estado de la vista actual de la presentación. El valor devuelto puede ser "edit" o "read". "editar" corresponde a cualquiera de las vistas en las que se pueden editar diapositivas: Normal, Clasificador de diapositivas o Vista de esquema. "lectura" corresponde a presentación con diapositivas o vista de lectura.

Devoluciones

void

Comentarios

Conjunto de requisitos: ActiveView

Puede desencadenar un evento al cambiar la vista.

Ejemplos

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)

Devuelve el archivo de documento entero en segmentos de hasta 4194304 bytes (4 MB). Para los complementos en iPad, el segmento de archivos se admite hasta 65536 (64 KB). Tenga en cuenta que, si especifica un tamaño del segmento del archivo superior al límite permitido, se producirá el error "Error interno".

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

Parámetros

fileType
Office.FileType

Formato en el que se devolverá el archivo

options
Office.GetFileOptions

Proporciona opciones para establecer el tamaño de los segmentos en los que se dividirá el documento.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el objeto File.

Devoluciones

void

Comentarios

Conjuntos de requisitos:

Para los complementos que se ejecutan en aplicaciones de Office distintas de Office en iPad, el método admite la getFileAsync obtención de archivos en segmentos de hasta 4194304 bytes (4 MB). Para los complementos que se ejecutan en aplicaciones de Office en iPad, el método admite la getFileAsync obtención de archivos en segmentos de hasta 65536 (64 KB).

El fileType parámetro se puede especificar mediante la enumeración Office.FileType o los valores de texto. Pero los valores posibles varían con la aplicación.

FileTypes admitidos, por plataforma

Office en la web Office en Windows Office en Mac Office en iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text No compatible
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

Ejemplos

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

Devuelve el archivo de documento entero en segmentos de hasta 4194304 bytes (4 MB). Para los complementos en iPad, el segmento de archivos se admite hasta 65536 (64 KB). Tenga en cuenta que, si especifica un tamaño del segmento del archivo superior al límite permitido, se producirá el error "Error interno".

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

Parámetros

fileType
Office.FileType

Formato en el que se devolverá el archivo

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el objeto File.

Devoluciones

void

Comentarios

Conjuntos de requisitos:

Para los complementos que se ejecutan en aplicaciones de Office distintas de Office en iPad, el método admite la getFileAsync obtención de archivos en segmentos de hasta 4194304 bytes (4 MB). Para los complementos que se ejecutan en aplicaciones de Office en iPad, el método admite la getFileAsync obtención de archivos en segmentos de hasta 65536 (64 KB).

El fileType parámetro se puede especificar mediante la enumeración Office.FileType o los valores de texto. Pero los valores posibles varían con la aplicación.

FileTypes admitidos, por plataforma

Office en la web Office en Windows Office en Mac Office en iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text No compatible
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

getFilePropertiesAsync(options, callback)

Obtiene las propiedades de archivo del documento actual.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es las propiedades del archivo (con la dirección URL que se encuentra en asyncResult.value.url).

Devoluciones

void

Comentarios

Conjuntos de requisitos: no en un conjunto

Obtiene la dirección URL del archivo con la propiedad asyncResult.value.urlurl .

getFilePropertiesAsync(callback)

Obtiene las propiedades de archivo del documento actual.

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

Parámetros

callback

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

Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es las propiedades del archivo (con la dirección URL que se encuentra en asyncResult.value.url).

Devoluciones

void

Comentarios

Conjuntos de requisitos: no en un conjunto

Obtiene la dirección URL del archivo con la propiedad asyncResult.value.urlurl .

Ejemplos

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

Solo documentos de proyecto. Obtenga el índice máximo de la colección de recursos del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el número de índice más alto de la colección de recursos del proyecto actual.

Devoluciones

void

getMaxResourceIndexAsync(callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de recursos del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el número de índice más alto de la colección de recursos del proyecto actual.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el índice máximo de la colección de tareas del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el número de índice más alto de la colección de tareas del proyecto actual.

Devoluciones

void

getMaxTaskIndexAsync(callback)

Solo documentos de proyecto. Obtenga el índice máximo de la colección de tareas del proyecto actual.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el número de índice más alto de la colección de tareas del proyecto actual.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtener campo Proyecto (por ejemplo, ProjectWebAccessURL).

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

Parámetros

fieldId

number

Campos de nivel de proyecto.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene la fieldValue propiedad , que representa el valor del campo especificado.

Devoluciones

void

getProjectFieldAsync(fieldId, callback)

Solo documentos de proyecto. Obtener campo Proyecto (por ejemplo, ProjectWebAccessURL).

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

Parámetros

fieldId

number

Campos de nivel de proyecto.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene la fieldValue propiedad , que representa el valor del campo especificado.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el GUID del recurso que tiene el índice especificado en la colección de recursos.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

resourceIndex

number

Índice del recurso en la colección de recursos del proyecto.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

getResourceByIndexAsync(resourceIndex, callback)

Solo documentos de proyecto. Obtenga el GUID del recurso que tiene el índice especificado en la colección de recursos.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

resourceIndex

number

Índice del recurso en la colección de recursos del proyecto.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el campo de recurso para el identificador de recurso proporcionado. (por ejemplo, ResourceName)

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

Parámetros

resourceId

string

Una cadena o un valor del identificador de recurso.

fieldId

number

Campos de recursos.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

getResourceFieldAsync(resourceId, fieldId, callback)

Solo documentos de proyecto. Obtenga el campo de recurso para el identificador de recurso proporcionado. (por ejemplo, ResourceName)

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

Parámetros

resourceId

string

Una cadena o un valor del identificador de recurso.

fieldId

number

Campos de recursos.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

Ejemplos

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

Lee los datos incluidos en la selección actual del documento.

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

Parámetros

coercionType
Office.CoercionType

El tipo de la estructura de datos que se debe devolver. Consulte la sección Comentarios para ver los tipos de coerción admitidos de cada aplicación.

options
Office.GetSelectedDataOptions

Proporciona opciones para personalizar qué datos se devuelven y cómo se les da formato.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado son los datos de la selección actual. Esto se devuelve en la estructura de datos o el formato especificado con el parámetro coercionType. (Vea la sección de comentarios para más información sobre la coerción de datos).

Devoluciones

void

Comentarios

Conjuntos de requisitos:

En la función de devolución de llamada que se pasa al método getSelectedDataAsync, puede usar las propiedades del objeto AsyncResult para devolver la siguiente información.

Propiedad Utilice
AsyncResult.value Siempre devuelve undefined porque no hay ningún objeto o datos que recuperar.
AsyncResult.status Determinar si la operación se ha completado correctamente o no.
AsyncResult.error Tener acceso a un objeto Error que proporcione información sobre el error si la operación no se ha llevado a cabo correctamente.
AsyncResult.asyncContext Defina un elemento de cualquier tipo que se devuelva en el objeto AsyncResult sin modificarse.

Los valores posibles para el parámetro Office.CoercionType varían según la aplicación de Office.

CoercionType Aplicaciones admitidas
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrices)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadena)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel en Windows y en Mac

Ejemplos

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

Lee los datos incluidos en la selección actual del documento.

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

Parámetros

coercionType
Office.CoercionType

El tipo de la estructura de datos que se debe devolver. Consulte la sección Comentarios para ver los tipos de coerción admitidos de cada aplicación.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado son los datos de la selección actual. Esto se devuelve en la estructura de datos o el formato especificado con el parámetro coercionType. (Vea la sección de comentarios para más información sobre la coerción de datos).

Devoluciones

void

Comentarios

Conjuntos de requisitos:

En la función de devolución de llamada que se pasa al método getSelectedDataAsync, puede usar las propiedades del objeto AsyncResult para devolver la siguiente información.

Propiedad Utilice
AsyncResult.value Siempre devuelve undefined porque no hay ningún objeto o datos que recuperar.
AsyncResult.status Determinar si la operación se ha completado correctamente o no.
AsyncResult.error Tener acceso a un objeto Error que proporcione información sobre el error si la operación no se ha llevado a cabo correctamente.
AsyncResult.asyncContext Defina un elemento de cualquier tipo que se devuelva en el objeto AsyncResult sin modificarse.

Los valores posibles para el parámetro Office.CoercionType varían según la aplicación de Office.

CoercionType Aplicaciones admitidas
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrices)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadena)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel en Windows y en Mac

getSelectedResourceAsync(options, callback)

Solo documentos de proyecto. Obtenga el identificador del recurso seleccionado actual.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

getSelectedResourceAsync(callback)

Solo documentos de proyecto. Obtenga el identificador del recurso seleccionado actual.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el identificador de tarea seleccionado actual.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

getSelectedTaskAsync(callback)

Solo documentos de proyecto. Obtenga el identificador de tarea seleccionado actual.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID del recurso como una cadena.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el tipo de vista seleccionado actual (por ejemplo, Gantt) y el nombre de la vista.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: : viewName el nombre de la vista, como una constante ProjectViewTypes. viewType - El tipo de vista, como el valor entero de una constante ProjectViewTypes.

Devoluciones

void

getSelectedViewAsync(callback)

Solo documentos de proyecto. Obtenga el tipo de vista seleccionado actual (por ejemplo, Gantt) y el nombre de la vista.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: : viewName el nombre de la vista, como una constante ProjectViewTypes. viewType - El tipo de vista, como el valor entero de una constante ProjectViewTypes.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el nombre de la tarea, el identificador de tarea de WSS y los nombres de recurso para un taskId determinado.

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: - taskName El nombre de la tarea. wssTaskId - El identificador de la tarea en la lista de tareas de SharePoint sincronizada. Si el proyecto no está sincronizado con una lista de tareas de SharePoint, el valor es 0. resourceNames - Lista separada por comas de los nombres de los recursos asignados a la tarea.

Devoluciones

void

getTaskAsync(taskId, callback)

Solo documentos de proyecto. Obtenga el nombre de la tarea, el identificador de tarea de WSS y los nombres de recurso para un taskId determinado.

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: - taskName El nombre de la tarea. wssTaskId - El identificador de la tarea en la lista de tareas de SharePoint sincronizada. Si el proyecto no está sincronizado con una lista de tareas de SharePoint, el valor es 0. resourceNames - Lista separada por comas de los nombres de los recursos asignados a la tarea.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el GUID de la tarea que tiene el índice especificado en la colección de tareas.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

taskIndex

number

Índice de la tarea en la colección de tareas del proyecto.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID de la tarea como una cadena.

Devoluciones

void

getTaskByIndexAsync(taskIndex, callback)

Solo documentos de proyecto. Obtenga el GUID de la tarea que tiene el índice especificado en la colección de tareas.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

taskIndex

number

Índice de la tarea en la colección de tareas del proyecto.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es el GUID de la tarea como una cadena.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga el campo de tarea para el identificador de tarea proporcionado. (por ejemplo, StartDate).

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

fieldId

number

Campos de tarea.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene la fieldValue propiedad , que representa el valor del campo especificado.

Devoluciones

void

getTaskFieldAsync(taskId, fieldId, callback)

Solo documentos de proyecto. Obtenga el campo de tarea para el identificador de tarea proporcionado. (por ejemplo, StartDate).

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

fieldId

number

Campos de tarea.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene la fieldValue propiedad , que representa el valor del campo especificado.

Devoluciones

void

Ejemplos

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

Solo documentos de proyecto. Obtenga la dirección URL de WSS y el nombre de la lista de tareas, el MPP también se sincroniza.

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

Parámetros

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: - listName el nombre de la lista de tareas de SharePoint sincronizada. serverUrl : la dirección URL de la lista de tareas sincronizadas de SharePoint.

Devoluciones

void

getWSSUrlAsync(callback)

Solo documentos de proyecto. Obtenga la dirección URL de WSS y el nombre de la lista de tareas, el MPP también se sincroniza.

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

Parámetros

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado contiene las siguientes propiedades: - listName el nombre de la lista de tareas de SharePoint sincronizada. serverUrl : la dirección URL de la lista de tareas sincronizadas de SharePoint.

Devoluciones

void

goToByIdAsync(id, goToType, options, callback)

Va al objeto o la ubicación que se haya especificado en el documento.

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

Parámetros

id

string | number

El identificador del objeto o la ubicación a la que dirigirse.

goToType
Office.GoToType

El tipo de ubicación a la que dirigirse.

options
Office.GoToByIdOptions

Proporciona opciones para seleccionar la ubicación a la que se navega.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es la vista actual.

Devoluciones

void

Comentarios

Conjunto de requisitos: no en un conjunto

PowerPoint no admite el método goToByIdAsync en vistas maestras.

El comportamiento causado por la opción selectionMode varía según la aplicación de Office:

En Excel: Office.SelectionMode.Selected selecciona todo el contenido del enlace o elemento con nombre. Office.SelectionMode.None: para los enlaces de texto, se selecciona la celda; para enlaces de matrices, los enlaces de tablas y los elementos con nombre, se selecciona la primera celda de datos (no la primera celda de la fila de encabezado de las tablas).

En PowerPoint: Office.SelectionMode.Selected selecciona el título de la diapositiva o el primer cuadro de texto de la diapositiva. Office.SelectionMode.None no selecciona nada.

En Word: Office.SelectionMode.Selected selecciona todo el contenido del enlace. Office.SelectionMode.None para los enlaces de texto; mueve el cursor al principio del texto; para los enlaces de matriz y los enlaces de la tabla, selecciona la primera celda de datos (no la primera celda de la fila de encabezado de las tablas).

goToByIdAsync(id, goToType, callback)

Va al objeto o la ubicación que se haya especificado en el documento.

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

Parámetros

id

string | number

El identificador del objeto o la ubicación a la que dirigirse.

goToType
Office.GoToType

El tipo de ubicación a la que dirigirse.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La value propiedad del resultado es la vista actual.

Devoluciones

void

Comentarios

Conjunto de requisitos: no en un conjunto

PowerPoint no admite el método goToByIdAsync en vistas maestras.

El comportamiento causado por la opción selectionMode varía según la aplicación de Office:

En Excel: Office.SelectionMode.Selected selecciona todo el contenido del enlace o elemento con nombre. Office.SelectionMode.None: para los enlaces de texto, se selecciona la celda; para enlaces de matrices, los enlaces de tablas y los elementos con nombre, se selecciona la primera celda de datos (no la primera celda de la fila de encabezado de las tablas).

En PowerPoint: Office.SelectionMode.Selected selecciona el título de la diapositiva o el primer cuadro de texto de la diapositiva. Office.SelectionMode.None no selecciona nada.

En Word: Office.SelectionMode.Selected selecciona todo el contenido del enlace. Office.SelectionMode.None para los enlaces de texto; mueve el cursor al principio del texto; para los enlaces de matriz y los enlaces de la tabla, selecciona la primera celda de datos (no la primera celda de la fila de encabezado de las tablas).

Ejemplos

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

Quita un controlador de eventos para el tipo de evento especificado.

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

Parámetros

eventType
Office.EventType

El tipo de evento. Para el documento puede ser "Document.SelectionChanged" o "Document.ActiveViewChanged".

options
Office.RemoveHandlerOptions

Proporciona opciones para determinar qué controladores o controladores de eventos se quitan.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Comentarios

Conjunto de requisitos: DocumentEvents

removeHandlerAsync(eventType, callback)

Quita un controlador de eventos para el tipo de evento especificado.

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

Parámetros

eventType
Office.EventType

El tipo de evento. Para el documento puede ser "Document.SelectionChanged" o "Document.ActiveViewChanged".

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Comentarios

Conjunto de requisitos: DocumentEvents

Ejemplos

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

Solo documentos de proyecto. Establezca el campo de recurso para el identificador de recurso especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

resourceId

string

Una cadena o un valor del identificador de recurso.

fieldId

number

Campos de recursos.

fieldValue

string | number | boolean | object

Valor del campo de destino.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Solo documentos de proyecto. Establezca el campo de recurso para el identificador de recurso especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

resourceId

string

Una cadena o un valor del identificador de recurso.

fieldId

number

Campos de recursos.

fieldValue

string | number | boolean | object

Valor del campo de destino.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Ejemplos

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

Escribe los datos especificados en la selección actual.

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

Parámetros

data

string | Office.TableData | any[][]

Datos que se van a establecer. Una cadena o un valor Office.CoercionType , una matriz 2D o un objeto TableData.

Si el valor pasado para data es:

  • Una string Se insertará texto sin formato o cualquier cosa que pueda convertirse en una string. En Excel, también puede especificar los datos como una fórmula válida para agregar esa fórmula a la celda seleccionada. Por ejemplo, al establecer data en "=SUM(A1:A5)", se calculará el total de los valores en el rango especificado. Pero cuando se establece una fórmula en la celda dependiente, después de hacerlo, no se puede leer desde la celda dependiente la fórmula agregada (o cualquier fórmula preexistente). Si se llama al método Document.getSelectedDataAsync en la celda seleccionada para leer sus datos, el método puede devolver solo los datos que se muestran en la celda (el resultado de la fórmula).

  • Una matriz de matrices ("matriz"): Se insertarán datos tabulares sin encabezados. Por ejemplo, para escribir datos en tres filas en dos columnas, puede pasar una matriz como esta: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. Para escribir una sola columna de tres filas, pase una matriz como esta: [["R1C1"], ["R2C1"], ["R3C1"]]

En Excel, también puede especificar datos como una matriz de matrices que contiene fórmulas válidas para agregarlos a las celdas seleccionadas. Por ejemplo, si no se va a sobrescribir ningún otro dato, al establecer data en [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] se agregarán estas dos fórmulas a la selección. Igual que cuando se establece una fórmula en una sola celda como "texto", no se pueden leer las fórmulas agregadas (o las fórmulas existentes) después de que se han configurado, solo se pueden leer los resultados de las fórmulas.

  • Un objeto TableData: Se insertará una tabla con encabezados. En Excel, si especifica fórmulas en el objeto TableData que pasa para el parámetro de datos, es posible que no obtenga los resultados esperados debido a la característica "columnas calculadas" de Excel, que duplica automáticamente las fórmulas dentro de una columna. Para solucionarlo cuando quiera escribir data que contiene fórmulas en una tabla seleccionada, intente especificar los datos como una matriz de matrices (en lugar de un objeto TableData) y especifique coercionType como Microsoft.Office.Matrix o "matrix". Sin embargo, esta técnica bloqueará la característica "columnas calculadas" solo cuando se cumpla una de las condiciones siguientes: (1) está escribiendo en todas las celdas de la columna o (2) ya hay al menos dos fórmulas diferentes en la columna.
options
Office.SetSelectedDataOptions

Proporciona opciones para insertar datos en la selección.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La propiedad AsyncResult.value siempre devuelve undefined porque no hay ningún objeto o datos que recuperar.

Devoluciones

void

Comentarios

Conjuntos de requisitos:

Comportamientos específicos de la aplicación

Las siguientes acciones específicas de la aplicación se aplican al escribir datos en una selección.

Aplicación Condición Comportamiento
Word Si no hay ninguna selección y el punto de inserción está en una ubicación válida, el especificado data se inserta en el punto de inserción. Si data es una cadena, se inserta el texto especificado.
Si data es una matriz de matrices ("matriz") o un objeto TableData, se inserta una nueva tabla Word.
Si los datos son HTML, se inserta el HTML especificado. (**Importante**: Si alguno de los HTML que inserta no es válido, Word no generará un error. Word insertará toda la cantidad de HTML que pueda y omitirá los datos no válidos).
Si data es Office Open XML, se inserta el XML especificado.
Si data es una secuencia de imagen codificada en Base64, se inserta la imagen especificada.
Si hay una selección Se reemplazará por el especificado data siguiendo las mismas reglas que antes.
Insertar imágenes Las imágenes insertadas se colocan en línea. Los parámetros imageLeft e imageTop se ignoran. La relación de aspecto de la imagen siempre está bloqueada. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.
Excel Si se selecciona una sola celda Si data es una cadena, el texto especificado se inserta como el valor de la celda actual.
Si data es una matriz de matrices ("matriz"), se inserta el conjunto especificado de filas y columnas, si no se sobrescribirá ningún otro dato de las celdas circundantes.
Si data es un objeto TableData, se inserta una nueva tabla de Excel con el conjunto especificado de filas y encabezados, si no se sobrescribirá ningún otro dato en las celdas circundantes.
Si se seleccionan varias celdas Si la forma no coincide con la forma de data, se devuelve un error.
Si la forma de la selección coincide exactamente con la forma de data, los valores de las celdas seleccionadas se actualizan en función de los valores de data.
Insertar imágenes Las imágenes insertadas son flotantes. Los parámetros position imageLeft e imageTop son relativos a las celdas seleccionadas actualmente. Los valores negativos imageLeft e imageTop están permitidos y es posible que Excel los reajuste para colocar la imagen dentro de una hoja de cálculo. La relación de aspecto de la imagen está bloqueada a menos que se indiquen los parámetros imageWidth e imageHeight. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.
Todos los demás casos Se devuelve un error.
Excel en la web Además de los comportamientos descritos para Excel anteriormente, estos límites se aplican al escribir datos en Excel en la Web El número total de celdas que puede escribir en una hoja de cálculo con el data parámetro no puede superar las 20 000 en una sola llamada a este método.
El número de grupos de formato pasados al cellFormat parámetro no puede superar los 100. Un único grupo de formato consta de un conjunto de formato aplicado a un rango de celdas especificado.
PowerPoint Insertar imagen Las imágenes insertadas son flotantes. Los parámetros position imageLeft e imageTop son opcionales, pero si se proporcionan, ambos deben estar presentes. Si solo se proporciona un valor, se ignorará. Los valores negativos imageLeft e imageTop están permitidos y pueden colocar una imagen fuera de una diapositiva. Si no se indica ningún parámetro opcional y la diapositiva tiene un marcador de posición, la imagen reemplazará el marcador de la diapositiva. La relación de aspecto de la imagen se bloqueará a menos que se indiquen los parámetros imageWidth e imageHeight. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.

Aplicaciones

Los valores posibles para el parámetro Office.CoercionType varían según la aplicación de Office.

CoercionType Aplicaciones admitidas
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrices)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint en la Web y en Windows
Office.CoercionType.Table (objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadena)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel en Windows y en Mac
  • PowerPoint en la Web, en Windows y en Mac
  • Word en Windows y en Mac

Ejemplos

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

Escribe los datos especificados en la selección actual.

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

Parámetros

data

string | Office.TableData | any[][]

Datos que se van a establecer. Una cadena o un valor Office.CoercionType , una matriz 2D o un objeto TableData.

Si el valor pasado para data es:

  • Una string Se insertará texto sin formato o cualquier cosa que pueda convertirse en una string. En Excel, también puede especificar los datos como una fórmula válida para agregar esa fórmula a la celda seleccionada. Por ejemplo, al establecer data en "=SUM(A1:A5)", se calculará el total de los valores en el rango especificado. Pero cuando se establece una fórmula en la celda dependiente, después de hacerlo, no se puede leer desde la celda dependiente la fórmula agregada (o cualquier fórmula preexistente). Si se llama al método Document.getSelectedDataAsync en la celda seleccionada para leer sus datos, el método puede devolver solo los datos que se muestran en la celda (el resultado de la fórmula).

  • Una matriz de matrices ("matriz"): Se insertarán datos tabulares sin encabezados. Por ejemplo, para escribir datos en tres filas en dos columnas, puede pasar una matriz como esta: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. Para escribir una sola columna de tres filas, pase una matriz como esta: [["R1C1"], ["R2C1"], ["R3C1"]]

En Excel, también puede especificar datos como una matriz de matrices que contiene fórmulas válidas para agregarlos a las celdas seleccionadas. Por ejemplo, si no se va a sobrescribir ningún otro dato, al establecer data en [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] se agregarán estas dos fórmulas a la selección. Igual que cuando se establece una fórmula en una sola celda como "texto", no se pueden leer las fórmulas agregadas (o las fórmulas existentes) después de que se han configurado, solo se pueden leer los resultados de las fórmulas.

  • Un objeto TableData: Se insertará una tabla con encabezados. En Excel, si especifica fórmulas en el objeto TableData que pasa para el parámetro de datos, es posible que no obtenga los resultados esperados debido a la característica "columnas calculadas" de Excel, que duplica automáticamente las fórmulas dentro de una columna. Para solucionarlo cuando quiera escribir data que contiene fórmulas en una tabla seleccionada, intente especificar los datos como una matriz de matrices (en lugar de un objeto TableData) y especifique coercionType como Microsoft.Office.Matrix o "matrix". Sin embargo, esta técnica bloqueará la característica "columnas calculadas" solo cuando se cumpla una de las condiciones siguientes: (1) está escribiendo en todas las celdas de la columna o (2) ya hay al menos dos fórmulas diferentes en la columna.
callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult. La propiedad AsyncResult.value siempre devuelve undefined porque no hay ningún objeto o datos que recuperar.

Devoluciones

void

Comentarios

Conjuntos de requisitos:

Comportamientos específicos de la aplicación

Las siguientes acciones específicas de la aplicación se aplican al escribir datos en una selección.

Aplicación Condición Comportamiento
Word Si no hay ninguna selección y el punto de inserción está en una ubicación válida, los "datos" especificados se insertan en el punto de inserción. Si data es una cadena, se inserta el texto especificado.
Si data es una matriz de matrices ("matriz") o un objeto TableData, se inserta una nueva tabla Word.
Si data es HTML, se inserta el HTML especificado. (**Importante**: Si alguno de los HTML que inserta no es válido, Word no generará un error. Word insertará toda la cantidad de HTML que pueda y omitirá los datos no válidos).
Si data es Office Open XML, se inserta el XML especificado.
Si data es una secuencia de imagen codificada en Base64, se inserta la imagen especificada.
Si hay una selección Se reemplazará por el especificado data siguiendo las mismas reglas que antes.
Insertar imágenes Las imágenes insertadas se colocan en línea. Los parámetros imageLeft e imageTop se ignoran. La relación de aspecto de la imagen siempre está bloqueada. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.
Excel Si se selecciona una sola celda Si data es una cadena, el texto especificado se inserta como el valor de la celda actual.
Si data es una matriz de matrices ("matriz"), se inserta el conjunto especificado de filas y columnas, si no se sobrescribirá ningún otro dato de las celdas circundantes.
Si data es un objeto TableData, se inserta una nueva tabla de Excel con el conjunto especificado de filas y encabezados, si no se sobrescribirá ningún otro dato en las celdas circundantes.
Si se seleccionan varias celdas Si la forma no coincide con la forma de data, se devuelve un error.
Si la forma de la selección coincide exactamente con la forma de data, los valores de las celdas seleccionadas se actualizan en función de los valores de data.
Insertar imágenes Las imágenes insertadas son flotantes. Los parámetros position imageLeft e imageTop son relativos a las celdas seleccionadas actualmente. Los valores negativos imageLeft e imageTop están permitidos y es posible que Excel los reajuste para colocar la imagen dentro de una hoja de cálculo. La relación de aspecto de la imagen está bloqueada a menos que se indiquen los parámetros imageWidth e imageHeight. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.
Todos los demás casos Se devuelve un error.
Excel en la web Además de los comportamientos descritos para Excel anteriormente, estos límites se aplican al escribir datos en Excel en la Web El número total de celdas que puede escribir en una hoja de cálculo con el data parámetro no puede superar las 20 000 en una sola llamada a este método.
El número de grupos de formato pasados al cellFormat parámetro no puede superar los 100. Un único grupo de formato consta de un conjunto de formato aplicado a un rango de celdas especificado.
PowerPoint Insertar imagen Las imágenes insertadas son flotantes. Los parámetros position imageLeft e imageTop son opcionales, pero si se proporcionan, ambos deben estar presentes. Si solo se proporciona un valor, se ignorará. Los valores negativos imageLeft e imageTop están permitidos y pueden colocar una imagen fuera de una diapositiva. Si no se indica ningún parámetro opcional y la diapositiva tiene un marcador de posición, la imagen reemplazará el marcador de la diapositiva. La relación de aspecto de la imagen se bloqueará a menos que se indiquen los parámetros imageWidth e imageHeight. Si solo se indica uno de los parámetros imageWidth e imageHeight, el otro valor se escalará automáticamente para conservar la relación de aspecto original.

Aplicaciones

Los valores posibles para el parámetro Office.CoercionType varían según la aplicación de Office.

CoercionType Aplicaciones admitidas
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (matriz de matrices)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint en la Web y en Windows
Office.CoercionType.Table (objeto TableData)
  • Excel
  • Word
Office.CoercionType.Text (cadena)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel en Windows y en Mac
  • PowerPoint en la Web, en Windows y en Mac
  • Word en Windows y en Mac

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

Solo documentos de proyecto. Establezca el campo de tarea para el identificador de tarea especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

fieldId

number

Campos de tarea.

fieldValue

string | number | boolean | object

Valor del campo de destino.

options
Office.AsyncContextOptions

Proporciona una opción para conservar los datos de contexto de cualquier tipo, sin cambios, para su uso en una devolución de llamada.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Solo documentos de proyecto. Establezca el campo de tarea para el identificador de tarea especificado.

Importante: Esta API solo funciona en Project en el escritorio de Windows.

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

Parámetros

taskId

string

Una cadena o un valor del identificador de tarea.

fieldId

number

Campos de tarea.

fieldValue

string | number | boolean | object

Valor del campo de destino.

callback

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

Opcional. Función que se invoca cuando se devuelve la devolución de llamada, cuyo único parámetro es de tipo Office.AsyncResult.

Devoluciones

void

Ejemplos

// 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);
    }
})();