Office.Document interface

アドインから対話操作するドキュメントを表す抽象クラス。

注釈

アプリケーション: Excel、PowerPoint、Project、Word

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

プロパティ

bindings

ドキュメントに定義されているバインドへのアクセスを提供するオブジェクトを取得します。

customXmlParts

ドキュメント内のカスタム XML パーツを表すオブジェクトを取得します。

mode

ドキュメントのモードを取得します。

settings

現在のドキュメントのコンテンツ アプリまたは作業ウィンドウ アプリの保存されているカスタム設定を表すオブジェクトを取得します。

url

Office アプリケーションが現在開いているドキュメントの URL を取得します。 URL が使用できない場合は null を返します。

メソッド

addHandlerAsync(eventType, handler, options, callback)

Document オブジェクト イベントのイベント ハンドラーを追加します。

addHandlerAsync(eventType, handler, callback)

Document オブジェクト イベントのイベント ハンドラーを追加します。

getActiveViewAsync(options, callback)

プレゼンテーションの現在のビューの状態を返します (編集または読み取り)。

getActiveViewAsync(callback)

プレゼンテーションの現在のビューの状態を返します (編集または読み取り)。

getFileAsync(fileType, options, callback)

ドキュメント ファイル全体を、最大で 4194304 バイト (4 MB) のスライスに分割して返します。 iPad のアドインの場合、ファイル スライスは最大 65536 (64 KB) までサポートされています。 許可されている制限を超えてスライス サイズを指定すると、"内部エラー" が発生しますのでご注意ください。

getFileAsync(fileType, callback)

ドキュメント ファイル全体を、最大で 4194304 バイト (4 MB) のスライスに分割して返します。 iPad のアドインの場合、ファイル スライスは最大 65536 (64 KB) までサポートされています。 許可されている制限を超えてスライス サイズを指定すると、"内部エラー" が発生しますのでご注意ください。

getFilePropertiesAsync(options, callback)

現在のドキュメントのファイル プロパティを取得します。

getFilePropertiesAsync(callback)

現在のドキュメントのファイル プロパティを取得します。

getMaxResourceIndexAsync(options, callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のリソースのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getMaxResourceIndexAsync(callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のリソースのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getMaxTaskIndexAsync(options, callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のタスクのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getMaxTaskIndexAsync(callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のタスクのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getProjectFieldAsync(fieldId, options, callback)

プロジェクト ドキュメントのみ。 [プロジェクトの取得] フィールド (ProjectWebAccessURL など)。

getProjectFieldAsync(fieldId, callback)

プロジェクト ドキュメントのみ。 [プロジェクトの取得] フィールド (ProjectWebAccessURL など)。

getResourceByIndexAsync(resourceIndex, options, callback)

プロジェクト ドキュメントのみ。 リソース コレクションで指定したインデックスを持つリソースの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getResourceByIndexAsync(resourceIndex, callback)

プロジェクト ドキュメントのみ。 リソース コレクションで指定したインデックスを持つリソースの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getResourceFieldAsync(resourceId, fieldId, options, callback)

プロジェクト ドキュメントのみ。 指定されたリソース ID のリソース フィールドを取得します。(Ex.ResourceName)

getResourceFieldAsync(resourceId, fieldId, callback)

プロジェクト ドキュメントのみ。 指定されたリソース ID のリソース フィールドを取得します。(Ex.ResourceName)

getSelectedDataAsync(coercionType, options, callback)

ドキュメントの現在の選択範囲に含まれるデータを読み取ります。

getSelectedDataAsync(coercionType, callback)

ドキュメントの現在の選択範囲に含まれるデータを読み取ります。

getSelectedResourceAsync(options, callback)

プロジェクト ドキュメントのみ。 現在選択されているリソースの ID を取得します。

getSelectedResourceAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されているリソースの ID を取得します。

getSelectedTaskAsync(options, callback)

プロジェクト ドキュメントのみ。 現在選択されているタスクの ID を取得します。

getSelectedTaskAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されているタスクの ID を取得します。

getSelectedViewAsync(options, callback)

プロジェクト ドキュメントのみ。 現在選択されている [ビューの種類] (ガントなど) と [ビュー名] を取得します。

getSelectedViewAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されている [ビューの種類] (ガントなど) と [ビュー名] を取得します。

getTaskAsync(taskId, options, callback)

プロジェクト ドキュメントのみ。 指定された taskId のタスク名、WSS タスク ID、ResourceNames を取得します。

getTaskAsync(taskId, callback)

プロジェクト ドキュメントのみ。 指定された taskId のタスク名、WSS タスク ID、ResourceNames を取得します。

getTaskByIndexAsync(taskIndex, options, callback)

プロジェクト ドキュメントのみ。 タスク コレクションで指定したインデックスを持つタスクの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getTaskByIndexAsync(taskIndex, callback)

プロジェクト ドキュメントのみ。 タスク コレクションで指定したインデックスを持つタスクの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

getTaskFieldAsync(taskId, fieldId, options, callback)

プロジェクト ドキュメントのみ。 指定されたタスク ID のタスク フィールドを取得します (例: StartDate)。

getTaskFieldAsync(taskId, fieldId, callback)

プロジェクト ドキュメントのみ。 指定されたタスク ID のタスク フィールドを取得します (例: StartDate)。

getWSSUrlAsync(options, callback)

プロジェクト ドキュメントのみ。 タスク リストの WSS URL とリスト名を取得します。MPP も同期されます。

getWSSUrlAsync(callback)

プロジェクト ドキュメントのみ。 タスク リストの WSS URL とリスト名を取得します。MPP も同期されます。

goToByIdAsync(id, goToType, options, callback)

ドキュメント内の指定されたオブジェクトまたは場所に移動します。

goToByIdAsync(id, goToType, callback)

ドキュメント内の指定されたオブジェクトまたは場所に移動します。

removeHandlerAsync(eventType, options, callback)

指定したイベントの種類のイベント ハンドラーを削除します。

removeHandlerAsync(eventType, callback)

指定したイベントの種類のイベント ハンドラーを削除します。

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

プロジェクト ドキュメントのみ。 指定したリソース ID にリソース フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

プロジェクト ドキュメントのみ。 指定したリソース ID にリソース フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

setSelectedDataAsync(data, options, callback)

指定したデータを現在の選択範囲に書き込みます。

setSelectedDataAsync(data, callback)

指定したデータを現在の選択範囲に書き込みます。

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

プロジェクト ドキュメントのみ。 指定したタスク ID にタスク フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

プロジェクト ドキュメントのみ。 指定したタスク ID にタスク フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

プロパティの詳細

bindings

ドキュメントに定義されているバインドへのアクセスを提供するオブジェクトを取得します。

bindings: Bindings;

プロパティ値

注釈

Document オブジェクトをスクリプトで直接インスタンス化することはありません。 To call members of the Document object to interact with the current document or worksheet, use Office.context.document in your script.

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

ドキュメント内のカスタム XML パーツを表すオブジェクトを取得します。

customXmlParts: CustomXmlParts;

プロパティ値

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

ドキュメントのモードを取得します。

mode: DocumentMode;

プロパティ値

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

現在のドキュメントのコンテンツ アプリまたは作業ウィンドウ アプリの保存されているカスタム設定を表すオブジェクトを取得します。

settings: Settings;

プロパティ値

url

Office アプリケーションが現在開いているドキュメントの URL を取得します。 URL が使用できない場合は null を返します。

url: string;

プロパティ値

string

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

メソッドの詳細

addHandlerAsync(eventType, handler, options, callback)

Document オブジェクト イベントのイベント ハンドラーを追加します。

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

パラメーター

eventType
Office.EventType

Document オブジェクト イベントの場合、eventType パラメーターは、 または Office.EventType.Document.ActiveViewChangedまたは、この列挙体の対応するテキスト値としてOffice.EventType.Document.SelectionChanged指定できます。

handler

any

追加するイベント ハンドラー関数。パラメーターは Office.DocumentSelectionChangedEventArgs 型のみです。 必須です。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

注釈

要件セット: DocumentEvents

各イベント ハンドラー関数の名前が一意である限り、指定した eventType に対して複数のイベント ハンドラーを追加できます。

addHandlerAsync(eventType, handler, callback)

Document オブジェクト イベントのイベント ハンドラーを追加します。

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

パラメーター

eventType
Office.EventType

Document オブジェクト イベントの場合、eventType パラメーターは、 または Office.EventType.Document.ActiveViewChangedまたは、この列挙体の対応するテキスト値としてOffice.EventType.Document.SelectionChanged指定できます。

handler

any

追加するイベント ハンドラー関数。パラメーターは Office.DocumentSelectionChangedEventArgs 型のみです。 必須です。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

注釈

要件セット: DocumentEvents

各イベント ハンドラー関数の名前が一意である限り、指定した eventType に対して複数のイベント ハンドラーを追加できます。

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

プレゼンテーションの現在のビューの状態を返します (編集または読み取り)。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、プレゼンテーションの現在のビューの状態です。 返される値は、"edit" または "read" のいずれかです。 "編集" は、スライドを編集できる任意のビュー (標準、スライド並べ替えツール、またはアウトライン ビュー) に対応します。 "読み取り" は、スライド ショーまたは閲覧ビューのいずれかに対応します。

戻り値

void

注釈

要件セット: ActiveView

ビューが変更されたときにイベントをトリガーできます。

getActiveViewAsync(callback)

プレゼンテーションの現在のビューの状態を返します (編集または読み取り)。

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

パラメーター

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、プレゼンテーションの現在のビューの状態です。 返される値は、"edit" または "read" のいずれかです。 "編集" は、スライドを編集できる任意のビュー (標準、スライド並べ替えツール、またはアウトライン ビュー) に対応します。 "読み取り" は、スライド ショーまたは閲覧ビューのいずれかに対応します。

戻り値

void

注釈

要件セット: ActiveView

ビューが変更されたときにイベントをトリガーできます。

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)

ドキュメント ファイル全体を、最大で 4194304 バイト (4 MB) のスライスに分割して返します。 iPad のアドインの場合、ファイル スライスは最大 65536 (64 KB) までサポートされています。 許可されている制限を超えてスライス サイズを指定すると、"内部エラー" が発生しますのでご注意ください。

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

パラメーター

fileType
Office.FileType

ファイルが返される形式

options
Office.GetFileOptions

ドキュメントが分割されるスライスのサイズを設定するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果の プロパティは value File オブジェクトです。

戻り値

void

注釈

要件セット:

iPad 上の Office 以外の Office アプリケーションで実行されているアドインの場合、このメソッドでは最大 getFileAsync 4194304 バイト (4 MB) のスライスでファイルを取得できます。 iPad 上の Office アプリで実行されているアドインの場合、 getFileAsync このメソッドでは最大 65536 (64 KB) のスライスでファイルを取得できます。

パラメーターは fileTypeOffice.FileType 列挙値またはテキスト値を使用して指定できます。 ただし、使用可能な値はアプリケーションによって異なります。

サポートされている FileTypes (プラットフォーム別)

Windows での Office Office on the web Office on iPad Office on Mac
Excel Compressed, Pdf, TextCompressed, Pdf Compressed, Pdf, Text
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, PdfCompressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, PdfCompressed, Pdf, Text

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

ドキュメント ファイル全体を、最大で 4194304 バイト (4 MB) のスライスに分割して返します。 iPad のアドインの場合、ファイル スライスは最大 65536 (64 KB) までサポートされています。 許可されている制限を超えてスライス サイズを指定すると、"内部エラー" が発生しますのでご注意ください。

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

パラメーター

fileType
Office.FileType

ファイルが返される形式

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果の プロパティは value File オブジェクトです。

戻り値

void

注釈

要件セット:

iPad 上の Office 以外の Office アプリケーションで実行されているアドインの場合、このメソッドでは最大 getFileAsync 4194304 バイト (4 MB) のスライスでファイルを取得できます。 iPad アプリ上の Office で実行されているアドインの場合、 getFileAsync このメソッドでは、最大 65536 (64 KB) のスライスでファイルを取得できます。

パラメーターは fileTypeOffice.FileType 列挙値またはテキスト値を使用して指定できます。 ただし、使用可能な値はアプリケーションによって異なります。

サポートされている FileTypes (プラットフォーム別)

Windows での Office Office on the web Office on iPad Office on Mac
Excel Compressed, Pdf, TextCompressed, Pdf Compressed, Pdf, Text
Powerpoint Compressed, Pdf Compressed, Pdf Compressed, PdfCompressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, PdfCompressed, Pdf, Text

getFilePropertiesAsync(options, callback)

現在のドキュメントのファイル プロパティを取得します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、ファイルのプロパティです (URL は にあります asyncResult.value.url)。

戻り値

void

注釈

要件セット: セットに含まれていない

url プロパティ asyncResult.value.urlを使用してファイルの URL を取得します。

getFilePropertiesAsync(callback)

現在のドキュメントのファイル プロパティを取得します。

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

パラメーター

callback

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

コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、ファイルのプロパティです (URL は にあります asyncResult.value.url)。

戻り値

void

注釈

要件セット: セットに含まれていない

url プロパティ asyncResult.value.urlを使用してファイルの URL を取得します。

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

プロジェクト ドキュメントのみ。 現在のプロジェクト内のリソースのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在のプロジェクトのリソース コレクション内で最も高いインデックス番号です。

戻り値

void

getMaxResourceIndexAsync(callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のリソースのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在のプロジェクトのリソース コレクション内で最も高いインデックス番号です。

戻り値

void

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

プロジェクト ドキュメントのみ。 現在のプロジェクト内のタスクのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在のプロジェクトのタスク コレクション内で最も高いインデックス番号です。

戻り値

void

getMaxTaskIndexAsync(callback)

プロジェクト ドキュメントのみ。 現在のプロジェクト内のタスクのコレクションの最大インデックスを取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在のプロジェクトのタスク コレクション内で最も高いインデックス番号です。

戻り値

void

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

プロジェクト ドキュメントのみ。 [プロジェクトの取得] フィールド (ProjectWebAccessURL など)。

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

パラメーター

fieldId

number

プロジェクト レベルのフィールド。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、指定したフィールドの値を表す プロパティが含まれていますfieldValue

戻り値

void

getProjectFieldAsync(fieldId, callback)

プロジェクト ドキュメントのみ。 [プロジェクトの取得] フィールド (ProjectWebAccessURL など)。

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

パラメーター

fieldId

number

プロジェクト レベルのフィールド。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、指定したフィールドの値を表す プロパティが含まれていますfieldValue

戻り値

void

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

プロジェクト ドキュメントのみ。 リソース コレクションで指定したインデックスを持つリソースの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

resourceIndex

number

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

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

getResourceByIndexAsync(resourceIndex, callback)

プロジェクト ドキュメントのみ。 リソース コレクションで指定したインデックスを持つリソースの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

resourceIndex

number

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

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

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

プロジェクト ドキュメントのみ。 指定されたリソース ID のリソース フィールドを取得します。(Ex.ResourceName)

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

パラメーター

resourceId

string

リソース ID の文字列または値。

fieldId

number

リソース フィールド。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

getResourceFieldAsync(resourceId, fieldId, callback)

プロジェクト ドキュメントのみ。 指定されたリソース ID のリソース フィールドを取得します。(Ex.ResourceName)

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

パラメーター

resourceId

string

リソース ID の文字列または値。

fieldId

number

リソース フィールド。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

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

ドキュメントの現在の選択範囲に含まれるデータを読み取ります。

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

パラメーター

coercionType
Office.CoercionType

返されるデータ構造の種類です。 各アプリケーションでサポートされている強制の種類については、「備考」セクションを参照してください。

options
Office.GetSelectedDataOptions

返されるデータと書式設定方法をカスタマイズするためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在の選択範囲のデータです。 これは、coercionType パラメーターで指定したデータ構造または形式で返されます。 (データの強制型変換の詳細については、「注釈」を参照してください)。

戻り値

void

注釈

要件セット:

getSelectedDataAsync メソッドに渡されるコールバック関数では、AsyncResult オブジェクトのプロパティを使用して、次の情報を返すことができます。

プロパティ 使用
AsyncResult.value 取得する undefined オブジェクトまたはデータがないため、常にが返されます
AsyncResult.status 操作の成功または失敗を判断する
AsyncResult.error 操作が失敗した場合にエラー情報を提供する Error オブジェクトにアクセスする
AsyncResult.asyncContext 変更されずに AsyncResult オブジェクトで返される任意の型の項目を定義する

Office.CoercionType パラメーターに使用できる値は、Office アプリケーションによって異なります。

CoercionType サポートされているアプリケーション
Office.CoercionType.Html - Word
Office.CoercionType.Matrix (配列の配列) -Excel
- Word
Office.CoercionType.Ooxml (Office Open XML) - Word
Office.CoercionType.SlideRange -Powerpoint
Office.CoercionType.Table (TableData オブジェクト) -Excel
- Word
Office.CoercionType.Text (string) -Excel
-Powerpoint
-プロジェクト
- Word
Office.CoercionType.XmlSvg - Windows と Mac の Excel
- Windows、Mac、および Web 上の PowerPoint

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

ドキュメントの現在の選択範囲に含まれるデータを読み取ります。

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

パラメーター

coercionType
Office.CoercionType

返されるデータ構造の種類です。 各アプリケーションでサポートされている強制の種類については、「備考」セクションを参照してください。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、現在の選択範囲のデータです。 これは、coercionType パラメーターで指定したデータ構造または形式で返されます。 (データの強制型変換の詳細については、「注釈」を参照してください)。

戻り値

void

注釈

要件セット:

getSelectedDataAsync メソッドに渡されるコールバック関数では、AsyncResult オブジェクトのプロパティを使用して、次の情報を返すことができます。

プロパティ 使用
AsyncResult.value 取得する undefined オブジェクトまたはデータがないため、常にが返されます
AsyncResult.status 操作の成功または失敗を判断する
AsyncResult.error 操作が失敗した場合にエラー情報を提供する Error オブジェクトにアクセスする
AsyncResult.asyncContext 変更されずに AsyncResult オブジェクトで返される任意の型の項目を定義する

Office.CoercionType パラメーターに使用できる値は、Office アプリケーションによって異なります。

CoercionType サポートされているアプリケーション
Office.CoercionType.Html - Word
Office.CoercionType.Matrix (配列の配列) -Excel
- Word
Office.CoercionType.Ooxml (Office Open XML) - Word
Office.CoercionType.SlideRange -Powerpoint
Office.CoercionType.Table (TableData オブジェクト) -Excel
- Word
Office.CoercionType.Text (string) -Excel
-Powerpoint
-プロジェクト
- Word
Office.CoercionType.XmlSvg - Windows と Mac の Excel
- Windows、Mac、および Web 上の PowerPoint

getSelectedResourceAsync(options, callback)

プロジェクト ドキュメントのみ。 現在選択されているリソースの ID を取得します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

getSelectedResourceAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されているリソースの ID を取得します。

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

パラメーター

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

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

プロジェクト ドキュメントのみ。 現在選択されているタスクの ID を取得します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

getSelectedTaskAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されているタスクの ID を取得します。

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

パラメーター

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのリソースの GUID です。

戻り値

void

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

プロジェクト ドキュメントのみ。 現在選択されている [ビューの種類] (ガントなど) と [ビュー名] を取得します。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果のプロパティには、次のプロパティが含まれています。 viewName - ProjectViewTypes 定数としてのビューの名前。 viewType - ProjectViewTypes 定数の整数値としてのビューの種類。

戻り値

void

getSelectedViewAsync(callback)

プロジェクト ドキュメントのみ。 現在選択されている [ビューの種類] (ガントなど) と [ビュー名] を取得します。

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

パラメーター

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果のプロパティには、次のプロパティが含まれています。 viewName - ProjectViewTypes 定数としてのビューの名前。 viewType - ProjectViewTypes 定数の整数値としてのビューの種類。

戻り値

void

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

プロジェクト ドキュメントのみ。 指定された taskId のタスク名、WSS タスク ID、ResourceNames を取得します。

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

パラメーター

taskId

string

タスク ID の文字列または値。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、次のプロパティが含まれます。 taskName - タスクの名前。 wssTaskId - 同期された SharePoint タスク リスト内のタスクの ID。 プロジェクトが SharePoint タスク リストと同期されていない場合、値は 0 です。 resourceNames - タスクに割り当てられているリソースの名前のコンマ区切りの一覧。

戻り値

void

getTaskAsync(taskId, callback)

プロジェクト ドキュメントのみ。 指定された taskId のタスク名、WSS タスク ID、ResourceNames を取得します。

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

パラメーター

taskId

string

タスク ID の文字列または値。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、次のプロパティが含まれます。 taskName - タスクの名前。 wssTaskId - 同期された SharePoint タスク リスト内のタスクの ID。 プロジェクトが SharePoint タスク リストと同期されていない場合、値は 0 です。 resourceNames - タスクに割り当てられているリソースの名前のコンマ区切りの一覧。

戻り値

void

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

プロジェクト ドキュメントのみ。 タスク コレクションで指定したインデックスを持つタスクの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

taskIndex

number

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

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのタスクの GUID です。

戻り値

void

getTaskByIndexAsync(taskIndex, callback)

プロジェクト ドキュメントのみ。 タスク コレクションで指定したインデックスを持つタスクの GUID を取得します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

taskIndex

number

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

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 、文字列としてのタスクの GUID です。

戻り値

void

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

プロジェクト ドキュメントのみ。 指定されたタスク ID のタスク フィールドを取得します (例: StartDate)。

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

パラメーター

taskId

string

タスク ID の文字列または値。

fieldId

number

タスク フィールド。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、指定したフィールドの値を表す プロパティが含まれていますfieldValue

戻り値

void

getTaskFieldAsync(taskId, fieldId, callback)

プロジェクト ドキュメントのみ。 指定されたタスク ID のタスク フィールドを取得します (例: StartDate)。

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

パラメーター

taskId

string

タスク ID の文字列または値。

fieldId

number

タスク フィールド。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果の プロパティには、指定したフィールドの値を表す プロパティが含まれていますfieldValue

戻り値

void

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

プロジェクト ドキュメントのみ。 タスク リストの WSS URL とリスト名を取得します。MPP も同期されます。

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

パラメーター

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果のプロパティには、同期された SharePoint タスク リストの名前というプロパティ listName が含まれています。 serverUrl - 同期された SharePoint タスク リストの URL。

戻り値

void

getWSSUrlAsync(callback)

プロジェクト ドキュメントのみ。 タスク リストの WSS URL とリスト名を取得します。MPP も同期されます。

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

パラメーター

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 value結果のプロパティには、同期された SharePoint タスク リストの名前というプロパティ listName が含まれています。 serverUrl - 同期された SharePoint タスク リストの URL。

戻り値

void

goToByIdAsync(id, goToType, options, callback)

ドキュメント内の指定されたオブジェクトまたは場所に移動します。

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

パラメーター

id

string | number

移動先のオブジェクトまたは場所の識別子です。

goToType
Office.GoToType

移動先の場所の型です。

options
Office.GoToByIdOptions

移動先の場所を選択するかどうかを示すオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 現在のビューです。

戻り値

void

注釈

要件セット: セットに含まれていない

PowerPoint では、マスター ビューの goToByIdAsync メソッドはサポートされていません。

selectionMode オプションによって発生する動作は、Office アプリケーションによって異なります。

Excel: Office.SelectionMode.Selected バインド内のすべてのコンテンツまたは名前付きアイテムを選択します。 Office.SelectionMode.None では、テキスト バインドの場合は、セルを選択します。マトリックス バインド、テーブル バインド、および名前付きアイテムの場合は、最初のデータ セルを選択します (テーブルの見出し行の最初のセルではありません)。

PowerPoint: Office.SelectionMode.Selected スライドのタイトルまたは最初のテキスト ボックスを選択します。 Office.SelectionMode.None は何も選択しません。

[Word: Office.SelectionMode.Selected バインド内のすべてのコンテンツを選択します。 Office.SelectionMode.None では、テキスト バインドの場合はテキストの最初までカーソルを移動します。マトリックス バインドとテーブル バインドの場合は、最初のデータ セルを選択します (テーブルの見出し行の最初のセルではありません)。

goToByIdAsync(id, goToType, callback)

ドキュメント内の指定されたオブジェクトまたは場所に移動します。

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

パラメーター

id

string | number

移動先のオブジェクトまたは場所の識別子です。

goToType
Office.GoToType

移動先の場所の型です。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 結果のプロパティは value 現在のビューです。

戻り値

void

注釈

要件セット: セットに含まれていない

PowerPoint では、マスター ビューの goToByIdAsync メソッドはサポートされていません。

selectionMode オプションによって発生する動作は、Office アプリケーションによって異なります。

Excel: Office.SelectionMode.Selected バインド内のすべてのコンテンツまたは名前付きアイテムを選択します。 Office.SelectionMode.None では、テキスト バインドの場合は、セルを選択します。マトリックス バインド、テーブル バインド、および名前付きアイテムの場合は、最初のデータ セルを選択します (テーブルの見出し行の最初のセルではありません)。

PowerPoint: Office.SelectionMode.Selected スライドのタイトルまたは最初のテキスト ボックスを選択します。 Office.SelectionMode.None は何も選択しません。

[Word: Office.SelectionMode.Selected バインド内のすべてのコンテンツを選択します。 Office.SelectionMode.None では、テキスト バインドの場合はテキストの最初までカーソルを移動します。マトリックス バインドとテーブル バインドの場合は、最初のデータ セルを選択します (テーブルの見出し行の最初のセルではありません)。

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

指定したイベントの種類のイベント ハンドラーを削除します。

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

パラメーター

eventType
Office.EventType

イベントの種類。 ドキュメントの場合は、'Document.SelectionChanged' または 'Document.ActiveViewChanged' を指定できます。

options
Office.RemoveHandlerOptions

削除されるイベント ハンドラーまたはハンドラーを決定するオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

注釈

要件セット: DocumentEvents

removeHandlerAsync(eventType, callback)

指定したイベントの種類のイベント ハンドラーを削除します。

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

パラメーター

eventType
Office.EventType

イベントの種類。 ドキュメントの場合は、'Document.SelectionChanged' または 'Document.ActiveViewChanged' を指定できます。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

注釈

要件セット: DocumentEvents

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

プロジェクト ドキュメントのみ。 指定したリソース ID にリソース フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

resourceId

string

リソース ID の文字列または値。

fieldId

number

リソース フィールド。

fieldValue

string | number | boolean | object

ターゲット フィールドの値。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

プロジェクト ドキュメントのみ。 指定したリソース ID にリソース フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

resourceId

string

リソース ID の文字列または値。

fieldId

number

リソース フィールド。

fieldValue

string | number | boolean | object

ターゲット フィールドの値。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

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

指定したデータを現在の選択範囲に書き込みます。

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

パラメーター

data

string | Office.TableData | any[][]

設定するデータ。 文字列または Office.CoercionType 値、2d 配列、または TableData オブジェクト。

に渡される値が次の data 場合:

  • 文字列: プレーン テキスト、または string に強制的に変換できるその他の値が挿入されます。 Excel では、有効な数式としてデータを指定して、選択したセルにその数式を追加することもできます。 例えば、data を "=SUM(A1:A5)" と設定すると、指定の範囲内の値が集計されます。 ただし、バインドされたセルで数式を設定する場合、その後、バインドされたセルからは追加された数式 (または既存の数式) を読み取ることができません。 選択したセルで Document.getSelectedDataAsync メソッドを呼び出してそのデータを読み取ると、このメソッドは (数式の結果である) セルに表示されたデータのみを返します。

  • 配列の配列 ("matrix"): ヘッダーなしの表形式データが挿入されます。 たとえば、2 つの列の 3 行にデータを書き込むには、[[["R1C1"、"R1C2"]、["R2C1"、"R2C2"]、["R3C1"、"R3C2"] のような配列を渡すことができます。 3 行の 1 列を書き込むには、[[["R1C1"]、["R2C1"]、["R3C1"]] のような配列を渡します。

Excel では、有効な数式を含む配列の配列としてデータを指定して、選択したセルに追加することもできます。 たとえば、他のデータが上書きされない場合、データを [["=SUM(A1:A5)","=AVERAGE(A1:A5)"] に設定すると、これら 2 つの数式が選択に追加されます。 Just as when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been set - you can only read the formulas' results.

  • TableData オブジェクト: ヘッダー付きのテーブルが挿入されます。 Excel では、データ パラメーターに渡す TableData オブジェクトで数式を指定した場合、Excel の "計算列" 機能により、列内の数式が自動的に複製されるため、予期した結果が得られない可能性があります。 選択したテーブルに数式を含むを記述 data する場合は、データを配列の配列 (TableData オブジェクトではなく) として指定し、coercionType を Microsoft.Office.Matrix または "matrix" として指定します。 ただし、この手法では、(1) 列のすべてのセルに書き込んでいるか、(2) 列に少なくとも 2 つの異なる数式が既に存在する場合にのみ、"計算列" 機能がブロックされます。
options
Office.SetSelectedDataOptions

選択範囲にデータを挿入する方法のオプションを提供します。

callback

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

オプション。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 取得するオブジェクトまたはデータがないため、AsyncResult.value プロパティは常にを返 undefined します。

戻り値

void

注釈

要件セット:

アプリケーション固有の動作

次のアプリケーション固有のアクションは、選択範囲にデータを書き込むときに適用されます。

Word 選択範囲がなく、挿入ポイントが有効な場所にある場合、指定した が挿入ポイントに挿入されます data が文字列の場合 data は、指定したテキストが挿入されます。
が配列 ("matrix") または TableData オブジェクトの配列である場合dataは、新しいWordテーブルが挿入されます。
データが HTML の場合、指定した HTML が挿入されます。 (**重要**: 挿入する HTML のいずれかが無効な場合、Wordエラーは発生しません。Wordは可能な限り多くの HTML を挿入し、無効なデータを省略します)。
が Office Open XML の場合 data 、指定した XML が挿入されます。
が base64 でエンコードされたイメージ ストリームの場合 data 、指定したイメージが挿入されます。
選択がある場合 上記と同じ規則に従って、指定した data に置き換えられます。
画像を挿入する 挿入されたイメージはインラインで配置されます。 imageLeft パラメーターと imageTop パラメーターは無視されます。 画像の縦横比は常に固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか 1 つのみが指定された場合、もう一方の値がスケーリングされて自動的に元の縦横比が維持されます。
Excel 1 つのセルが選択されている場合 が文字列の場合 data 、指定したテキストが現在のセルの値として挿入されます。
が配列の配列 ("matrix") の場合 data 、周囲のセル内の他のデータが上書きされない場合、指定した行と列のセットが挿入されます。
が TableData オブジェクトの場合 data 、周囲のセル内の他のデータが上書きされない場合は、指定した行とヘッダーのセットを含む新しい Excel テーブルが挿入されます。
複数のセルが選択されている場合 図形が の図形 dataと一致しない場合は、エラーが返されます。
選択範囲の図形が の図形 dataと正確に一致する場合は、 の値に基づいて、選択したセルの値 dataが更新されます。
画像を挿入する 挿入された画像は浮動になります。 position imageLeft パラメーターと imageTop パラメーターは、現在選択されているセルを基準にしています。 imageLeft と imageTop は負の値にすることもでき、その場合は、画像がワークシート内に収まるようにするために Excel によって再調整される可能性があります。 画像の縦横比は、 imageWidth と imageHeight パラメーターの両方が指定されない限り固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか一方が指定されている場合、もう一方の値は、元の縦横比を維持するように自動調整されます。
その他のすべてのケース エラーが返されます。
Excel on the web 上記の Excel の動作に加えて、これらの制限は、Excel on the webでデータを書き込むときに適用されます パラメーターを使用してワークシート data に書き込めるセルの合計数は、このメソッドの 1 回の呼び出しで 20,000 を超えることはできません。
パラメーターに cellFormat 渡される書式設定グループの数は、100 を超えることはできません。 1 つの書式設定グループは、指定のセル範囲に適用される書式設定のセットから構成されます。
PowerPoint 画像の挿入 挿入された画像は浮動になります。 position imageLeft パラメーターと imageTop パラメーターは省略可能ですが、指定した場合は両方とも存在する必要があります。 1 つの値しか指定されない場合、それは無視されます。 imageLeft と imageTop は負の値にすることもでき、その場合は、画像がスライドの外に配置される可能性があります。 オプションのパラメーターが指定されず、スライドにプレースホルダがある場合は、画像によってスライドのプレースホルダが置き換えられます。 画像の縦横比は、 imageWidth パラメーターと imageHeight パラメーターの両方が指定されない限り固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか一方が指定されている場合、もう一方の値は、元の縦横比を維持するように自動調整されます。

アプリケーション

Office.CoercionType パラメーターに使用できる値は、Office アプリケーションによって異なります。

CoercionType サポートされているアプリケーション
Office.CoercionType.Html - Word
Office.CoercionType.Matrix (配列の配列) -Excel
- Word
Office.CoercionType.Ooxml (Office Open XML) - Word
Office.CoercionType.SlideRange - PowerPoint on the webと Windows の場合
Office.CoercionType.Table (TableData オブジェクト) -Excel
- Word
Office.CoercionType.Text (string) -Excel
-Powerpoint
-プロジェクト
- Word
Office.CoercionType.XmlSvg - Windows と Mac の Excel
- Windows、Mac、および Web 上の PowerPoint
- Windows と Mac のWord

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

指定したデータを現在の選択範囲に書き込みます。

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

パラメーター

data

string | Office.TableData | any[][]

設定するデータ。 文字列または Office.CoercionType 値、2d 配列、または TableData オブジェクト。

に渡される値が次の data 場合:

  • 文字列: プレーン テキスト、または string に強制的に変換できるその他の値が挿入されます。 Excel では、有効な数式としてデータを指定して、選択したセルにその数式を追加することもできます。 例えば、data を "=SUM(A1:A5)" と設定すると、指定の範囲内の値が集計されます。 ただし、バインドされたセルで数式を設定する場合、その後、バインドされたセルからは追加された数式 (または既存の数式) を読み取ることができません。 選択したセルで Document.getSelectedDataAsync メソッドを呼び出してそのデータを読み取ると、このメソッドは (数式の結果である) セルに表示されたデータのみを返します。

  • 配列の配列 ("matrix"): ヘッダーなしの表形式データが挿入されます。 たとえば、2 つの列の 3 行にデータを書き込むには、[[["R1C1"、"R1C2"]、["R2C1"、"R2C2"]、["R3C1"、"R3C2"] のような配列を渡すことができます。 3 行の 1 列を書き込むには、[[["R1C1"]、["R2C1"]、["R3C1"]] のような配列を渡します。

Excel では、有効な数式を含む配列の配列としてデータを指定して、選択したセルに追加することもできます。 たとえば、他のデータが上書きされない場合、データを [["=SUM(A1:A5)","=AVERAGE(A1:A5)"] に設定すると、これら 2 つの数式が選択に追加されます。 Just as when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been set - you can only read the formulas' results.

  • TableData オブジェクト: ヘッダー付きのテーブルが挿入されます。 Excel では、データ パラメーターに渡す TableData オブジェクトで数式を指定した場合、Excel の "計算列" 機能により、列内の数式が自動的に複製されるため、予期した結果が得られない可能性があります。 選択したテーブルに数式を含むを記述 data する場合は、データを配列の配列 (TableData オブジェクトではなく) として指定し、coercionType を Microsoft.Office.Matrix または "matrix" として指定します。 ただし、この手法では、(1) 列のすべてのセルに書き込んでいるか、(2) 列に少なくとも 2 つの異なる数式が既に存在する場合にのみ、"計算列" 機能がブロックされます。
callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。 取得するオブジェクトまたはデータがないため、AsyncResult.value プロパティは常にを返 undefined します。

戻り値

void

注釈

要件セット:

アプリケーション固有の動作

次のアプリケーション固有のアクションは、選択範囲にデータを書き込むときに適用されます。

Word 選択範囲がなく、挿入ポイントが有効な場所にある場合、指定した 'data' が挿入ポイントに挿入されます。 が文字列の場合 data は、指定したテキストが挿入されます。
が配列 ("matrix") または TableData オブジェクトの配列である場合dataは、新しいWordテーブルが挿入されます。
が HTML の場合 data 、指定した HTML が挿入されます。 (**重要**: 挿入する HTML のいずれかが無効な場合、Wordエラーは発生しません。Wordは可能な限り多くの HTML を挿入し、無効なデータを省略します)。
が Office Open XML の場合 data 、指定した XML が挿入されます。
が base64 でエンコードされたイメージ ストリームの場合 data 、指定したイメージが挿入されます。
選択がある場合 上記と同じ規則に従って、指定した data に置き換えられます。
画像を挿入する 挿入されたイメージはインラインで配置されます。 imageLeft パラメーターと imageTop パラメーターは無視されます。 画像の縦横比は常に固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか 1 つのみが指定された場合、もう一方の値がスケーリングされて自動的に元の縦横比が維持されます。
Excel 1 つのセルが選択されている場合 が文字列の場合 data 、指定したテキストが現在のセルの値として挿入されます。
が配列の配列 ("matrix") の場合 data 、周囲のセル内の他のデータが上書きされない場合、指定した行と列のセットが挿入されます。
が TableData オブジェクトの場合 data 、周囲のセル内の他のデータが上書きされない場合は、指定した行とヘッダーのセットを含む新しい Excel テーブルが挿入されます。
複数のセルが選択されている場合 図形が の図形 dataと一致しない場合は、エラーが返されます。
選択範囲の図形が の図形 dataと正確に一致する場合は、 の値に基づいて、選択したセルの値 dataが更新されます。
画像を挿入する 挿入された画像は浮動になります。 position imageLeft パラメーターと imageTop パラメーターは、現在選択されているセルを基準にしています。 imageLeft と imageTop は負の値にすることもでき、その場合は、画像がワークシート内に収まるようにするために Excel によって再調整される可能性があります。 画像の縦横比は、 imageWidth と imageHeight パラメーターの両方が指定されない限り固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか一方が指定されている場合、もう一方の値は、元の縦横比を維持するように自動調整されます。
その他のすべてのケース エラーが返されます。
Excel on the web 上記の Excel の動作に加えて、これらの制限は、Excel on the webでデータを書き込むときに適用されます パラメーターを使用してワークシート data に書き込めるセルの合計数は、このメソッドの 1 回の呼び出しで 20,000 を超えることはできません。
パラメーターに cellFormat 渡される書式設定グループの数は、100 を超えることはできません。 1 つの書式設定グループは、指定のセル範囲に適用される書式設定のセットから構成されます。
PowerPoint 画像の挿入 挿入された画像は浮動になります。 position imageLeft パラメーターと imageTop パラメーターは省略可能ですが、指定した場合は両方とも存在する必要があります。 1 つの値しか指定されない場合、それは無視されます。 imageLeft と imageTop は負の値にすることもでき、その場合は、画像がスライドの外に配置される可能性があります。 オプションのパラメーターが指定されず、スライドにプレースホルダがある場合は、画像によってスライドのプレースホルダが置き換えられます。 画像の縦横比は、 imageWidth パラメーターと imageHeight パラメーターの両方が指定されない限り固定されます。 imageWidth パラメーターと imageHeight パラメーターのいずれか一方が指定されている場合、もう一方の値は、元の縦横比を維持するように自動調整されます。

アプリケーション

Office.CoercionType パラメーターに使用できる値は、Office アプリケーションによって異なります。

CoercionType サポートされているアプリケーション
Office.CoercionType.Html - Word
Office.CoercionType.Matrix (配列の配列) -Excel
- Word
Office.CoercionType.Ooxml (Office Open XML) - Word
Office.CoercionType.SlideRange - PowerPoint on the webと Windows の場合
Office.CoercionType.Table (TableData オブジェクト) -Excel
- Word
Office.CoercionType.Text (string) -Excel
-Powerpoint
-プロジェクト
- Word
Office.CoercionType.XmlSvg - Windows と Mac の Excel
- Windows、Mac、および Web 上の PowerPoint
- Windows と Mac のWord

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

プロジェクト ドキュメントのみ。 指定したタスク ID にタスク フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

taskId

string

タスク ID の文字列または値。

fieldId

number

タスク フィールド。

fieldValue

string | number | boolean | object

ターゲット フィールドの値。

options
Office.AsyncContextOptions

コールバックで使用するために、任意の型のコンテキスト データを変更せずに保持するためのオプションを提供します。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

プロジェクト ドキュメントのみ。 指定したタスク ID にタスク フィールドを設定します。

重要: この API は、Windows デスクトップ上の Project 2016 でのみ機能します。

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

パラメーター

taskId

string

タスク ID の文字列または値。

fieldId

number

タスク フィールド。

fieldValue

string | number | boolean | object

ターゲット フィールドの値。

callback

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

省略可能です。 コールバックから戻るときに呼び出される関数。パラメーターは Office.AsyncResult 型のみです。

戻り値

void

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