Office.Document interface 
表示与外接程序交互的文档的抽象类。
注解
应用程序:Excel、PowerPoint、Project Word
示例
// Get the Document object with the Common APIs.
const document : Office.Document = Office.context.document;
属性
| bindings | 获取提供对文档中定义的绑定的访问的对象。 | 
| custom | 获取文档中表示自定义 XML 部件的对象。 | 
| mode | 获取文档所处的模式。 | 
| settings | 获取用于表示当前文档的内容或任务窗格应用程序的已保存自定义设置的对象。 | 
| url | 获取 Office 应用程序当前已打开的文档的 URL。 如果 URL 不可用,则返回 null。 | 
方法
属性详细信息
bindings
获取提供对文档中定义的绑定的访问的对象。
bindings: Bindings;属性值
注解
不直接在脚本中实例化 Document 对象。 若要调用 Document 对象的成员以便与当前文档或工作表交互,请使用脚本中的 Office.context.document。
示例
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
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.SelectionChanged 或 Office.EventType.Document.ActiveViewChanged,或指定此枚举的相应文本值。
- 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.SelectionChanged 或 Office.EventType.Document.ActiveViewChanged,或指定此枚举的相应文本值。
- 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://free.blessedness.top/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://free.blessedness.top/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://free.blessedness.top/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”。 “编辑”对应于可在其中编辑幻灯片的任何视图:“普通”、“幻灯片排序器”或“大纲视图”。 “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”。 “编辑”对应于可在其中编辑幻灯片的任何视图:“普通”、“幻灯片排序器”或“大纲视图”。 “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
注解
要求集:
- 使用 - Office.FileType.Compressed) 时的 CompressedFile (
- 使用 - Office.FileType.Text) 时的 TextFile (
对于在除 iPad 上的 Office 以外的 Office 应用程序中运行的外接程序, getFileAsync 方法支持将文件以最大4194304字节的切片 (4 MB) 。 对于在 iPad 上的 Office 应用中运行的加载项, getFileAsync 方法支持在高达 65536 (64 KB) 的切片中获取文件。
              fileType可以使用 Office.FileType 枚举或文本值指定 参数。 但可能的值因应用程序而异。
支持的 FileTypes(按平台)
| Office 网页版 | Windows 版 Office | Mac 版 Office | iPad 版 Office | |
|---|---|---|---|---|
| 胜过 | Compressed,Pdf | Compressed,Pdf,Text | Compressed,Pdf,Text | 不支持 | 
| PowerPoint | Compressed | Compressed,Pdf | Compressed,Pdf | Compressed,Pdf | 
| Word | Compressed,Pdf,Text | Compressed,Pdf,Text | Compressed,Pdf,Text | Compressed,Pdf | 
示例
// 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
注解
要求集:
- 使用 - Office.FileType.Compressed) 时的 CompressedFile (
- 使用 - Office.FileType.Text) 时的 TextFile (
对于在除 iPad 上的 Office 以外的 Office 应用程序中运行的外接程序, getFileAsync 方法支持将文件以最大4194304字节的切片 (4 MB) 。 对于在 iPad 上的 Office 应用中运行的加载项, getFileAsync 方法支持在高达 65536 (64 KB) 的切片中获取文件。
              fileType可以使用 Office.FileType 枚举或文本值指定 参数。 但可能的值因应用程序而异。
支持的 FileTypes(按平台)
| Office 网页版 | Windows 版 Office | Mac 版 Office | iPad 版 Office | |
|---|---|---|---|---|
| 胜过 | Compressed,Pdf | Compressed,Pdf,Text | Compressed,Pdf,Text | 不支持 | 
| PowerPoint | Compressed | Compressed,Pdf | Compressed,Pdf | Compressed,Pdf | 
| Word | Compressed,Pdf,Text | Compressed,Pdf,Text | Compressed,Pdf,Text | Compressed,Pdf | 
		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。
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。
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。
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。
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。
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。
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 的资源字段。 (例如 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 的资源字段。 (例如 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
注解
要求集:
- 使用 - Office.CoercionType.Html) 时 htmlCoercion (
- 使用 - Office.CoercionType.Matrix) 时,MatrixCoercion (
- 使用 - Office.CoercionType.Ooxml) 时 OoxmlCoercion (
- 使用 - Office.CoercionType.Table) 时的 TableCoercion (
- 使用 - Office.CoercionType.Text) 时 TextCoercion (
在传递给 getSelectedDataAsync 方法的回调函数中,可以使用 AsyncResult 对象的属性返回以下信息。
| 属性 | 用途 | 
|---|---|
| AsyncResult.value | 始终返回 , undefined因为没有要检索的对象或数据。 | 
| AsyncResult.status | 确定操作是成功还是失败。 | 
| AsyncResult.error | 如果操作失败,则访问提供错误信息的 Error 对象。 | 
| AsyncResult.asyncContext | 定义在 AsyncResult 对象中返回的任何类型的项,而不进行更改。 | 
Office.CoercionType 参数的可能值因 Office 应用程序而异。
| CoercionType | 支持的应用程序 | 
|---|---|
| Office.CoercionType.Html | 
 | 
| Office.CoercionType.Matrix(数组) | 
 | 
| Office.CoercionType.Ooxml(Office Open XML) | 
 | 
| Office.CoercionType.SlideRange | 
 | 
| Office.CoercionType.Table(TableData 对象) | 
 | 
| Office.CoercionType.Text(字符串) | 
 | 
| Office.CoercionType.XmlSvg | 
 | 
示例
// 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
注解
要求集:
- 使用 - Office.CoercionType.Html) 时 htmlCoercion (
- 使用 - Office.CoercionType.Matrix) 时,MatrixCoercion (
- 使用 - Office.CoercionType.Ooxml) 时 OoxmlCoercion (
- 使用 - Office.CoercionType.Table) 时的 TableCoercion (
- 使用 - Office.CoercionType.Text) 时 TextCoercion (
在传递给 getSelectedDataAsync 方法的回调函数中,可以使用 AsyncResult 对象的属性返回以下信息。
| 属性 | 用途 | 
|---|---|
| AsyncResult.value | 始终返回 , undefined因为没有要检索的对象或数据。 | 
| AsyncResult.status | 确定操作是成功还是失败。 | 
| AsyncResult.error | 如果操作失败,则访问提供错误信息的 Error 对象。 | 
| AsyncResult.asyncContext | 定义在 AsyncResult 对象中返回的任何类型的项,而不进行更改。 | 
Office.CoercionType 参数的可能值因 Office 应用程序而异。
| CoercionType | 支持的应用程序 | 
|---|---|
| Office.CoercionType.Html | 
 | 
| Office.CoercionType.Matrix(数组) | 
 | 
| Office.CoercionType.Ooxml(Office Open XML) | 
 | 
| Office.CoercionType.SlideRange | 
 | 
| Office.CoercionType.Table(TableData 对象) | 
 | 
| Office.CoercionType.Text(字符串) | 
 | 
| Office.CoercionType.XmlSvg | 
 | 
		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 和 ResourceName。
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 和 ResourceName。
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。
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。
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结果的 属性包含以下属性: listName - 同步的 SharePoint 任务列表的名称。 
              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结果的 属性包含以下属性: listName - 同步的 SharePoint 任务列表的名称。 
              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 不支持 Master 视图中的 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 不支持 Master 视图中的 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。
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。
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 方法以读取其数据,方法可能仅返回在单元格中显示的数据(即公式的结果)。 
- 数组的数组(“矩阵”): 将插入不带标题的表数据。 例如,若要将数据写入两列中的三行,可以传递如下数组:[“R1C1”, “R1C2”],[“R2C1”, “R2C2”],[“R3C1”, “R3C2”]]。 若要编写包含三行的单列,请传递如下数组:[[“R1C1”],[“R2C1”],[“R3C1”]] 
在 Excel 中,还可以将数据指定为数组,其中包含用于将有效公式添加到所选单元格的数组。 例如,如果不覆盖任何其他数据,将 data 设置为 [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] 会将这两个公式添加到选择中。 与在单个单元格上将公式设置为“text”一样,设置后你将无法读取添加的公式(或任何已有公式),只能读取公式的结果。
- TableData 对象: 将插入带标题的表格。 在 Excel 中,如果在为数据参数传递的 TableData 对象中指定公式,则可能由于 Excel 的“计算列”功能而无法获得预期的结果,该功能会自动复制列中的公式。 若要在将包含公式写入 data所选表时解决此问题,请尝试将数据指定为数组数组 (而不是 TableData 对象) ,并将 coercionType 指定为 Microsoft.Office.Matrix 或“matrix”。 但是,仅当满足以下条件之一时,此方法才会阻止“计算列”功能: (1) 写入列的所有单元格,或者 (2) 列中至少有两个不同的公式。
- options
- Office.SetSelectedDataOptions
提供有关如何将数据插入所选内容的选项。
- callback
- 
				(result: Office.AsyncResult<void>) => void 
可选。 回调返回时调用的函数,其唯一参数的类型为 Office.AsyncResult。 AsyncResult.value 属性始终返回 undefined ,因为没有要检索的对象或数据。
返回
void
注解
要求集:
- HtmlCoercion,使用 - Office.CoercionType.Html) 时 (
- 使用 - Office.CoercionType.Image) 时 imageCoercion 1.1 (
- 使用 - Office.CoercionType.Matrix) 时,MatrixCoercion (
- 使用 - Office.CoercionType.Ooxml) 时 OoxmlCoercion (
- 使用 - Office.CoercionType.Table) 时的 TableCoercion (
- 使用 - Office.CoercionType.Text) 时 TextCoercion (
- 使用 - Office.CoercionType.XmlSvg) 时 imageCoercion 1.2 (
特定于应用程序的行为
将数据写入选定内容时,以下特定于应用程序的作适用。
| 应用程序 | 条件 | 行为 | 
|---|---|---|
| Word | 如果没有选择,并且插入点位于有效位置,则指定的 data将插入到插入点 | 如果 data是字符串,则插入指定的文本。 | 
| 如果 data是数组 (“matrix”) 或 TableData 对象,则插入新的Word表。 | ||
| 如果 data为 HTML,则插入指定的 HTML。  (**重要说明**:如果插入的任何 HTML 无效,Word不会引发错误。Word将尽可能多地插入 HTML,并省略任何无效数据) 。 | ||
| 如果 data为 Office Open XML,则插入指定的 XML。 | ||
| 如果 data是 Base64 编码的图像流,则插入指定的图像。 | ||
| 如果有选择 | 将按照上述相同规则将其替换为指定的 data。 | |
| 插入图像 | 插入的图像将内联放置。 imageLeft 和 imageTop 参数将被忽略。 图像的纵横比始终被锁定。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | |
| Excel | 如果选择了单个单元格 | 如果 data是字符串,则指定文本将作为当前单元格的值插入。 | 
| 如果 data是数组 (“matrix”) ,则插入指定的行和列集,如果周围单元格中没有其他数据将被覆盖。 | ||
| 如果 data是 TableData 对象,则插入具有指定行和标题集的新 Excel 表(如果周围单元格中没有其他数据将被覆盖)。 | ||
| 如果选择了多个单元格 | 如果形状与 的形状 data不匹配,则返回错误。 | |
| 如果所选内容的形状与 的形状 data完全匹配,则会根据 中的data值更新所选单元格的值。 | ||
| 插入图像 | 插入的图像为浮动图像。 imageLeft 和 imageTop 参数相对于当前所选单元格。 允许 imageLeft 和 imageTop 的值为负数,将由 Excel 重新调整在工作表内放置的图像位置。 除非 imageWidth 和 imageHeight 参数均已提供,否则将锁定图像的纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | |
| 所有其他情况 | 返回错误。 | |
| Excel 网页版 | 除了上述 Excel 行为外,这些限制也适用于在 Excel web 版 中写入数据 | 在对此方法的单个调用中,可以使用 参数写入工作表 data的单元格总数不能超过 20,000 个。 | 
| 传递给 cellFormat参数的格式设置组数不能超过 100。 每个格式设置组由应用于特定单元格范围的一组格式组成。 | ||
| PowerPoint | 插入图像 | 插入的图像为浮动图像。 imageLeft 和 imageTop 参数的位置是可选的,但如果提供,则两者都应存在。 如果提供单个值,则它将被忽略。 允许 imageLeft 和 imageTop 的值为负数,且可以将图像放置在幻灯片的外部。 如果未给定任何可选参数,并且幻灯片有一个占位符,则图像将替换幻灯片中的占位符。 除非 imageWidth和 imageHeight 参数均已提供,否则将锁定图像纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | 
应用
Office.CoercionType 参数的可能值因 Office 应用程序而异。
| CoercionType | 支持的应用程序 | 
|---|---|
| Office.CoercionType.Html | 
 | 
| Office.CoercionType.Matrix(数组) | 
 | 
| Office.CoercionType.Ooxml(Office Open XML) | 
 | 
| Office.CoercionType.SlideRange | 
 | 
| Office.CoercionType.Table(TableData 对象) | 
 | 
| Office.CoercionType.Text(字符串) | 
 | 
| Office.CoercionType.XmlSvg | 
 | 
示例
// 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 方法以读取其数据,方法可能仅返回在单元格中显示的数据(即公式的结果)。 
- 数组的数组(“矩阵”): 将插入不带标题的表数据。 例如,若要将数据写入两列中的三行,可以传递如下数组:[“R1C1”, “R1C2”],[“R2C1”, “R2C2”],[“R3C1”, “R3C2”]]。 若要编写包含三行的单列,请传递如下数组:[[“R1C1”],[“R2C1”],[“R3C1”]] 
在 Excel 中,还可以将数据指定为数组,其中包含用于将有效公式添加到所选单元格的数组。 例如,如果不覆盖任何其他数据,将 data 设置为 [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] 会将这两个公式添加到选择中。 与在单个单元格上将公式设置为“text”一样,设置后你将无法读取添加的公式(或任何已有公式),只能读取公式的结果。
- TableData 对象: 将插入带标题的表格。 在 Excel 中,如果在为数据参数传递的 TableData 对象中指定公式,则可能由于 Excel 的“计算列”功能而无法获得预期的结果,该功能会自动复制列中的公式。 若要在将包含公式写入 data所选表时解决此问题,请尝试将数据指定为数组数组 (而不是 TableData 对象) ,并将 coercionType 指定为 Microsoft.Office.Matrix 或“matrix”。 但是,仅当满足以下条件之一时,此方法才会阻止“计算列”功能: (1) 写入列的所有单元格,或者 (2) 列中至少有两个不同的公式。
- callback
- 
				(result: Office.AsyncResult<void>) => void 
可选。 回调返回时调用的函数,其唯一参数的类型为 Office.AsyncResult。 AsyncResult.value 属性始终返回 undefined ,因为没有要检索的对象或数据。
返回
void
注解
要求集:
- HtmlCoercion,使用 - Office.CoercionType.Html) 时 (
- 使用 - Office.CoercionType.Image) 时 ImageCoercion (
- 使用 - Office.CoercionType.Matrix) 时,MatrixCoercion (
- 使用 - Office.CoercionType.Ooxml) 时 OoxmlCoercion (
- 使用 - Office.CoercionType.Table) 时的 TableCoercion (
- 使用 - Office.CoercionType.Text) 时 TextCoercion (
- 使用 - Office.CoercionType.XmlSvg) 时 imageCoercion 1.2 (
特定于应用程序的行为
将数据写入选定内容时,以下特定于应用程序的作适用。
| 应用程序 | 条件 | 行为 | 
|---|---|---|
| Word | 如果没有选择,并且插入点位于有效位置,则指定的 data将插入到插入点 | 如果 data是字符串,则插入指定的文本。 | 
| 如果 data是数组 (“matrix”) 或 TableData 对象,则插入新的Word表。 | ||
| 如果 data为 HTML,则插入指定的 HTML。  (**重要说明**:如果插入的任何 HTML 无效,Word不会引发错误。Word将尽可能多地插入 HTML,并省略任何无效数据) 。 | ||
| 如果 data为 Office Open XML,则插入指定的 XML。 | ||
| 如果 data是 Base64 编码的图像流,则插入指定的图像。 | ||
| 如果有选择 | 将按照上述相同规则将其替换为指定的 data。 | |
| 插入图像 | 插入的图像将内联放置。 imageLeft 和 imageTop 参数将被忽略。 图像的纵横比始终被锁定。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | |
| Excel | 如果选择了单个单元格 | 如果 data是字符串,则指定文本将作为当前单元格的值插入。 | 
| 如果 data是数组 (“matrix”) ,则插入指定的行和列集,如果周围单元格中没有其他数据将被覆盖。 | ||
| 如果 data是 TableData 对象,则插入具有指定行和标题集的新 Excel 表(如果周围单元格中没有其他数据将被覆盖)。 | ||
| 如果选择了多个单元格 | 如果形状与 的形状 data不匹配,则返回错误。 | |
| 如果所选内容的形状与 的形状 data完全匹配,则会根据 中的data值更新所选单元格的值。 | ||
| 插入图像 | 插入的图像为浮动图像。 imageLeft 和 imageTop 参数相对于当前所选单元格。 允许 imageLeft 和 imageTop 的值为负数,将由 Excel 重新调整在工作表内放置的图像位置。 除非 imageWidth 和 imageHeight 参数均已提供,否则将锁定图像的纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | |
| 所有其他情况 | 返回错误。 | |
| Excel 网页版 | 除了上述 Excel 行为外,这些限制也适用于在 Excel web 版 中写入数据 | 在对此方法的单个调用中,可以使用 参数写入工作表 data的单元格总数不能超过 20,000 个。 | 
| 传递给 cellFormat参数的格式设置组数不能超过 100。 每个格式设置组由应用于特定单元格范围的一组格式组成。 | ||
| PowerPoint | 插入图像 | 插入的图像为浮动图像。 imageLeft 和 imageTop 参数的位置是可选的,但如果提供,则两者都应存在。 如果提供单个值,则它将被忽略。 允许 imageLeft 和 imageTop 的值为负数,且可以将图像放置在幻灯片的外部。 如果未给定任何可选参数,并且幻灯片有一个占位符,则图像将替换幻灯片中的占位符。 除非 imageWidth和 imageHeight 参数均已提供,否则将锁定图像纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。 | 
应用
Office.CoercionType 参数的可能值因 Office 应用程序而异。
| CoercionType | 支持的应用程序 | 
|---|---|
| Office.CoercionType.Html | 
 | 
| Office.CoercionType.Matrix(数组) | 
 | 
| Office.CoercionType.Ooxml(Office Open XML) | 
 | 
| Office.CoercionType.SlideRange | 
 | 
| Office.CoercionType.Table(TableData 对象) | 
 | 
| Office.CoercionType.Text(字符串) | 
 | 
| Office.CoercionType.XmlSvg | 
 | 
		setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)
	      
	仅项目文档。 为指定的任务 ID 设置任务域。
重要说明:此 API 仅适用于 Windows 桌面上的 Project。
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。
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);
    }
})();