Office.Document interface
表示与外接程序交互的文档的抽象类。
本文内容
注解
主机:Excel、PowerPoint、Project、Word
属性
获取提供对文档中定义的绑定的访问的对象。
获取文档中表示自定义 XML 部件的对象。
获取文档所处的模式。
获取用于表示当前文档的内容或任务窗格应用程序的已保存自定义设置的对象。
获取主机应用程序当前打开的文档的 URL。 如果 URL 不可用,则返回 null。
方法
属性详细信息
bindings
获取提供对文档中定义的绑定的访问的对象。
bindings: Bindings;
属性值
注解
请勿直接在脚本中实例化 Document 对象。 若要调用 Document 对象的成员以便与当前文档或工作表交互,请使用脚本中的 Office.context.document。
示例
function displayAllBindings() {
Office.context.document.bindings.getAllAsync(function (asyncResult) {
var bindingString = '';
for (var i in asyncResult.value) {
bindingString += asyncResult.value[i].id + '\n';
}
write('Existing bindings: ' + bindingString);
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
customXmlParts
获取文档中表示自定义 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:
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// Get information about the document.
showDocumentProperties();
});
};
// Get the document mode and the URL of the active project.
function showDocumentProperties() {
var output = String.format(
'The document mode is {0}.
The URL of the active project is {1}.',
Office.context.document.mode,
Office.context.document.url);
$('#message').html(output);
}
})();
settings
获取用于表示当前文档的内容或任务窗格应用程序的已保存自定义设置的对象。
settings: Settings;
属性值
url
获取主机应用程序当前打开的文档的 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;
参数
对于 Document 对象事件,eventType 参数可指定为 Office.EventType.Document.SelectionChanged 或 Office.EventType.Document.ActiveViewChanged或此枚举的相应文本值。
handler
any
要添加的事件处理程序函数,其唯一的参数的类型Office.DocumentSelectionChangedEventArgs. 必需。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
注解
只要每个事件处理程序函数的名称是唯一的,就可以为指定的 eventType 添加多个事件处理程序。
addHandlerAsync(eventType, handler, callback)
添加 Document 对象事件的事件处理程序。
addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void;
参数
对于 Document 对象事件,eventType 参数可指定为 Office.EventType.Document.SelectionChanged 或 Office.EventType.Document.ActiveViewChanged或此枚举的相应文本值。
handler
any
要添加的事件处理程序函数,其唯一的参数的类型Office.DocumentSelectionChangedEventArgs. 必需。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
注解
只要每个事件处理程序函数的名称是唯一的,就可以为指定的 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:
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
Office.context.document.addHandlerAsync(
Office.EventType.ResourceSelectionChanged,
getResourceGuid);
});
};
// Get the GUID of the selected resource and display it in the add-in.
function getResourceGuid() {
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
$('#message').html(result.value);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
// For a complete code sample that shows how to use a ResourceSelectionChanged
// event handler in a Project add-in, see "Create your first task pane add-in
// for Project 2013 by using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example adds a handler for the TaskSelectionChanged event.
// When the task selection changes in the document, it gets the GUID of the
// selected task.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
//
(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:
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
Office.context.document.addHandlerAsync(
Office.EventType.ViewSelectionChanged,
getActiveView);
getActiveView();
});
};
// Get the name and type of the active view and display it in the add-in.
function getActiveView() {
Office.context.document.getSelectedViewAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var output = String.format(
'View name: {0}
View type: {1}',
result.value.viewName, result.value.viewType);
$('#message').html(output);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
// For an example that shows how to use a ViewSelectionChanged event handler in a
// Project add-in, see "Create your first task pane add-in for Project 2013 by
// using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example uses addHandlerAsync to add an event handler for the ViewSelectionChanged event.
// When the active view changes, the handler checks the view type. It enables a button if the view is a resource
// view and disables the button if it isn't a resource view. Choosing the button gets the GUID of the selected
// resource and displays it in the add-in.
// The example assumes that your add-in has a reference to the jQuery library and that the following page controls
// are defined in the content div in the page body:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
// Add a ViewSelectionChanged event handler.
Office.context.document.addHandlerAsync(
Office.EventType.ViewSelectionChanged,
getActiveView);
$('#get-info').click(getResourceGuid);
// This example calls the handler on page load to get the active view
// of the default page.
getActiveView();
});
};
// Activate the button based on the active view type of the document.
// This is the ViewSelectionChanged event handler.
function getActiveView() {
Office.context.document.getSelectedViewAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var viewType = result.value.viewType;
if (viewType == 6 || // ResourceForm
viewType == 7 || // ResourceSheet
viewType == 8 || // ResourceGraph
viewType == 15) { // ResourceUsage
$('#get-info').removeAttr('disabled');
}
else {
$('#get-info').attr('disabled', 'disabled');
}
var output = String.format(
'View name: {0}
View type: {1}',
result.value.viewName, viewType);
$('#message').html(output);
}
}
);
}
// Get the GUID of the currently selected resource and display it in the add-in.
function getResourceGuid() {
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
$('#message').html('Resource GUID: ' + result.value);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
// For a complete code sample that shows how to use a ViewSelectionChanged event handler in a Project add-in,
// see "Create your first task pane add-in for Project by using a text editor."
// https://docs.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
getActiveViewAsync(options, callback)
返回演示文稿(编辑或读取)的当前视图的状态。
getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是演示文稿的当前视图的状态。 返回的值可以是"edit"或"read"。 "编辑"对应于可在其中编辑幻灯片的任何视图,如普通视图或大纲视图。 "read"对应于幻灯片放映或阅读视图。
返回
void
注解
当视图更改时可以触发事件。
getActiveViewAsync(callback)
返回演示文稿(编辑或读取)的当前视图的状态。
getActiveViewAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是演示文稿的当前视图的状态。 返回的值可以是"edit"或"read"。 "编辑"对应于可在其中编辑幻灯片的任何视图,如普通视图或大纲视图。 "read"对应于幻灯片放映或阅读视图。
返回
void
注解
当视图更改时可以触发事件。
示例
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) => void): void;
参数
将返回文件的格式
提供用于设置文档将划分为的切片大小的选项。
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是 File 对象。
返回
void
注解
要求集:
使用时 (CompressedFile 文件 Office.FileType.Compressed)
TextFile (使用时显示 Office.FileType.Text)
对于在 Office 主机应用程序(而非 iPad 上的 Office)中运行的外接程序,此方法支持以切片方式获取文件,最多为 getFileAsync 4194304 字节 (4 MB) 。 对于在 iPad 上的 Office 应用中运行的外接程序,此方法支持以切片方式获取文件,最多为 getFileAsync 65536 (64 KB) 。
可以使用 fileType Office.FileType 枚举或文本值指定参数。 但可能的值因主机而异:
受支持的 FileTypes(按平台)Windows 版 OfficeOffice 网页版iPad 版 OfficeMac 版 Office
ExcelCompressed, Pdf, TextCompressed, PdfCompressed, Pdf, Text
PowerPointCompressed, PdfCompressed, PdfCompressed, PdfCompressed, Pdf
WordCompressed, Pdf, TextCompressed, Pdf, TextCompressedCompressed, Pdf, Text
示例
// The following example gets the document in Office Open XML ("compressed") format in 65536 bytes (64 KB) slices.
// Note: The implementation of app.showNotification in this example is from the Visual Studio template for Office Add-ins.
function getDocumentAsCompressed() {
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 /*64 KB*/ },
function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
var myFile = result.value;
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);
// Get the file slices.
getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
else {
app.showNotification("Error:", result.error.message);
}
});
}
function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
file.getSliceAsync(nextSlice, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!gotAllSlices) { // Failed to get all slices, no need to continue.
return;
}
// Got one slice, store it in a temporary array.
// (Or you can do something else, such as
// send it to a third-party server.)
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
// All slices have been received.
file.closeAsync();
onGotAllSlices(docdataSlices);
}
else {
getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
}
else {
gotAllSlices = false;
file.closeAsync();
app.showNotification("getSliceAsync Error:", sliceResult.error.message);
}
});
}
function onGotAllSlices(docdataSlices) {
var docdata = [];
for (var i = 0; i < docdataSlices.length; i++) {
docdata = docdata.concat(docdataSlices[i]);
}
var fileContent = new String();
for (var j = 0; j < docdata.length; j++) {
fileContent += String.fromCharCode(docdata[j]);
}
// Now all the file content is stored in 'fileContent' variable,
// you can do something with it, such as print, fax...
}
// The following example gets the document in PDF format.
Office.context.document.getFileAsync(Office.FileType.Pdf,
function(result) {
if (result.status == "succeeded") {
var myFile = result.value;
var sliceCount = myFile.sliceCount;
app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);
// Now, you can call getSliceAsync to download the files,
// as described in the previous code segment (compressed format).
myFile.closeAsync();
}
else {
app.showNotification("Error:", result.error.message);
}
}
);
getFileAsync(fileType, callback)
以高达 4194304 字节 (4 MB) 的切片形式返回整个文档文件。 对于 iPad 上的外接程序,文件切片支持高达 65536 (64 KB) 。 请注意,若指定文件切片的大小上限超出允许限制,则会导致一个“内部错误”故障。
getFileAsync(fileType: FileType, callback?: (result: AsyncResult) => void): void;
参数
将返回文件的格式
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是 File 对象。
返回
void
注解
要求集:
使用时 (CompressedFile 文件 Office.FileType.Compressed)
TextFile (使用时显示 Office.FileType.Text)
对于在 Office 主机应用程序(而非 iPad 上的 Office)中运行的外接程序,此方法支持以切片方式获取文件,最多为 getFileAsync 4194304 字节 (4 MB) 。 对于在 iPad 上的 Office 中运行的外接程序,此方法支持以切片方式获取文件,最多为 getFileAsync 65536 (64 KB) 。
可以使用 fileType Office.FileType 枚举或文本值指定参数。 但可能的值因主机而异:
受支持的 FileTypes(按平台)Windows 版 OfficeOffice 网页版iPad 版 OfficeMac 版 Office
ExcelCompressed, Pdf, TextCompressed, PdfCompressed, Pdf, Text
PowerPointCompressed, PdfCompressed, PdfCompressed, PdfCompressed, Pdf
WordCompressed, Pdf, TextCompressed, Pdf, TextCompressedCompressed, Pdf, Text
getFilePropertiesAsync(options, callback)
获取当前文档的文件属性。
getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是文件的属性 (URL 位于asyncResult.value.url).
返回
void
注解
使用 url 属性获取文件的 URL asyncResult.value.url.
getFilePropertiesAsync(callback)
获取当前文档的文件属性。
getFilePropertiesAsync(callback?: (result: AsyncResult) => void): void;
参数
回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是文件的属性 (URL 位于asyncResult.value.url).
返回
void
注解
使用 url 属性获取文件的 URL asyncResult.value.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) {
var fileUrl = asyncResult.value.url;
if (fileUrl == "") {
showMessage("The file hasn't been saved yet. Save the file and try again");
}
else {
showMessage(fileUrl);
}
});
}
getMaxResourceIndexAsync(options, callback)
仅项目文档。 获取当前项目中的资源集合的最大索引。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前项目的资源集合中的最高索引号。
返回
void
getMaxResourceIndexAsync(callback)
仅项目文档。 获取当前项目中的资源集合的最大索引。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getMaxResourceIndexAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
var resourceGuids = ;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#get-info').click(getResourceInfo);
});
};
// Get the maximum resource index, and then get the resource GUIDs.
function getResourceInfo() {
getMaxResourceIndex().then(
function (data) {
getResourceGuids(data);
}
);
}
// Get the maximum index of the resources for the current project.
function getMaxResourceIndex() {
var defer = $.Deferred();
Office.context.document.getMaxResourceIndexAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get each resource GUID, and then display the GUIDs in the add-in.
// There is no 0 index for resources, so start with index 1.
function getResourceGuids(maxResourceIndex) {
var defer = $.Deferred();
for (var i = 1; i <= maxResourceIndex; i++) {
getResourceGuid(i);
}
return defer.promise();
function getResourceGuid(index) {
Office.context.document.getResourceByIndexAsync(index,
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
resourceGuids.push(result.value);
if (index == maxResourceIndex) {
defer.resolve();
$('#message').html(resourceGuids.toString());
}
}
else {
onError(result.error);
}
}
);
}
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getMaxTaskIndexAsync(options, callback)
仅项目文档。 获取当前项目中的任务集合的最大索引。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前项目的任务集合中的最高索引号。
返回
void
getMaxTaskIndexAsync(callback)
仅项目文档。 获取当前项目中的任务集合的最大索引。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getMaxTaskIndexAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
var taskGuids = ;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#get-info').click(getTaskInfo);
});
};
// Get the maximum task index, and then get the task GUIDs.
function getTaskInfo() {
getMaxTaskIndex().then(
function (data) {
getTaskGuids(data);
}
);
}
// Get the maximum index of the tasks for the current project.
function getMaxTaskIndex() {
var defer = $.Deferred();
Office.context.document.getMaxTaskIndexAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get each task GUID, and then display the GUIDs in the add-in.
function getTaskGuids(maxTaskIndex) {
var defer = $.Deferred();
for (var i = 0; i <= maxTaskIndex; i++) {
getTaskGuid(i);
}
return defer.promise();
function getTaskGuid(index) {
Office.context.document.getTaskByIndexAsync(index,
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
taskGuids.push(result.value);
if (index == maxTaskIndex) {
defer.resolve();
$('#message').html(taskGuids.toString());
}
}
else {
onError(result.error);
}
}
);
}
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getProjectFieldAsync(fieldId, options, callback)
仅项目文档。 获取项目域 (例如。 ProjectWebAccessURL) 。
getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
fieldId
number
项目级域。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性包含 fieldValue 属性,它表示指定字段的值。
返回
void
getProjectFieldAsync(fieldId, callback)
仅项目文档。 获取项目域 (例如。 ProjectWebAccessURL) 。
getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult) => void): void;
参数
fieldId
number
项目级域。
callback
(result: Office.AsyncResult) => 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:
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// Get information for the active project.
getProjectInformation();
});
};
// Get the specified fields for the active project.
function getProjectInformation() {
var fields =
[Office.ProjectProjectFields.Start,
Office.ProjectProjectFields.Finish,
Office.ProjectProjectFields.GUID];
var fieldValues = ['Start: ', 'Finish: ', 'GUID: '];
var index = 0;
getField();
// Get each field, and then display the field values in the add-in.
function getField() {
if (index == fields.length) {
var output = '';
for (var i = 0; i < fieldValues.length; i++) {
output += fieldValues[i] + '
';
}
$('#message').html(output);
}
else {
Office.context.document.getProjectFieldAsync(
fields[index],
function (result) {
// If the call is successful, get the field value and then get the next field.
if (result.status === Office.AsyncResultStatus.Succeeded) {
fieldValues[index] += result.value.fieldValue;
getField(index++);
}
else {
onError(result.error);
}
}
);
}
}
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getResourceByIndexAsync(resourceIndex, options, callback)
仅项目文档。 获取资源集合中具有指定索引的资源的 GUID。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
resourceIndex
number
The index of the resource in the collection of resources for the project.
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是作为字符串的资源的 GUID。
返回
void
getResourceByIndexAsync(resourceIndex, callback)
仅项目文档。 获取资源集合中具有指定索引的资源的 GUID。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult) => void): void;
参数
resourceIndex
number
The index of the resource in the collection of resources for the project.
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
var resourceGuids = ;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#get-info').click(getResourceInfo);
});
};
// Get the maximum resource index, and then get the resource GUIDs.
function getResourceInfo() {
getMaxResourceIndex().then(
function (data) {
getResourceGuids(data);
}
);
}
// Get the maximum index of the resources for the current project.
function getMaxResourceIndex() {
var defer = $.Deferred();
Office.context.document.getMaxResourceIndexAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get each resource GUID, and then display the GUIDs in the add-in.
// There is no 0 index for resources, so start with index 1.
function getResourceGuids(maxResourceIndex) {
var defer = $.Deferred();
for (var i = 1; i <= maxResourceIndex; i++) {
getResourceGuid(i);
}
return defer.promise();
function getResourceGuid(index) {
Office.context.document.getResourceByIndexAsync(index,
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
resourceGuids.push(result.value);
if (index == maxResourceIndex) {
defer.resolve();
$('#message').html(resourceGuids.toString());
}
}
else {
onError(result.error);
}
}
);
}
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getResourceFieldAsync(resourceId, fieldId, options, callback)
仅项目文档。 获取提供的资源 ID 的资源字段。 (Ex.ResourceName)
getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
resourceId
string
资源 ID 的字符串或值。
fieldId
number
资源域。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是作为字符串的资源的 GUID。
返回
void
getResourceFieldAsync(resourceId, fieldId, callback)
仅项目文档。 获取提供的资源 ID 的资源字段。 (Ex.ResourceName)
getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult) => void): void;
参数
resourceId
string
资源 ID 的字符串或值。
fieldId
number
资源域。
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getResourceInfo);
});
};
// Get the GUID of the resource and then get the resource fields.
function getResourceInfo() {
getResourceGuid().then(
function (data) {
getResourceFields(data);
}
);
}
// Get the GUID of the selected resource.
function getResourceGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get the specified fields for the selected resource.
function getResourceFields(resourceGuid) {
var targetFields =
[Office.ProjectResourceFields.Name,
Office.ProjectResourceFields.Units,
Office.ProjectResourceFields.BaseCalendar];
var fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
var index = 0;
getField();
// Get each field, and then display the field values in the add-in.
function getField() {
if (index == targetFields.length) {
var output = '';
for (var i = 0; i < fieldValues.length; i++) {
output += fieldValues[i] + '
';
}
$('#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(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void;
参数
要返回的数据结构的类型。 请参阅每个主机支持的强制类型的备注部分。
提供用于自定义返回的数据及其格式设置方式的选项。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前选定内容中的数据。 这将以使用 coercionType 参数指定的数据结构或格式返回。 (请参阅备注,了解有关数据强制的详细信息。)
返回
void
注解
要求集:
使用时 (HtmlCoercionOffice.CoercionType.Html)
使用时 (MatrixCoercionOffice.CoercionType.Matrix)
使用时 (OoxmlCoercionOffice.CoercionType.Ooxml)
使用时 (TableCoercionOffice.CoercionType.Table)
使用时 (TextCoercionOffice.CoercionType.Text)
在传递给 getSelectedDataAsync 方法的回调函数中,您可以使用 AsyncResult 对象的属性返回以下信息。
属性 用于...
AsyncResult.value 始终返回 undefined,这是因为没有要检索的对象或数据。
AsyncResult.status 确定操作是成功还是失败。
AsyncResult.error 如果操作失败,则访问提供错误信息的 Error 对象。
AsyncResult.asyncContext 在 AsyncResult 对象中未经改动的返回的任何类型的用户定义项。
主机 支持的 coercionType
Excel、PowerPoint、Project 和 Word `Office.CoercionType.Text` (字符串)
Excel 和 Word `Office.CoercionType.Matrix` (数组的数组)
Excel 和 Word `Office.CoercionType.Table` (TableData 对象)
Word `Office.CoercionType.Html`
Word `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint 网页和 Windows `Office.CoercionType.SlideRange`
Excel、PowerPoint 和 Word `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.
// Display the user's current selection.
function showSelection() {
Office.context.document.getSelectedDataAsync(
"text", // coercionType
{valueFormat: "unformatted", // valueFormat
filterType: "all"}, // filterType
function (result) { // callback
var dataValue;
dataValue = result.value;
write('Selected data is: ' + dataValue);
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
// To read the value of the current selection, you need to write a callback function that reads the selection.
// The following example shows how to:
// 1. Pass an anonymous callback function that reads the value of the current selection
// to the callback parameter of the getSelectedDataAsync method.
// 2. Read the selection as text, unformatted, and not filtered.
// 3. Display the value on the add-in's page.
function getText() {
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
{ valueFormat: "unformatted", filterType: "all" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
write(error.name + ": " + error.message);
}
else {
// Get selected data.
var dataValue = asyncResult.value;
write('Selected data is ' + dataValue);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
// The following code example gets the values of the selected cells. It uses the optional
// asyncContext parameter to pass some text to the callback function.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getSelectedText);
});
};
// Get the text from the selected cells in the document, and display it in the add-in.
function getSelectedText() {
Office.context.document.getSelectedDataAsync(
Office.CoercionType.Text,
{asyncContext: 'Some related info'},
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var output = String.format(
'Selected text: {0}
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(coercionType: Office.CoercionType, callback?: (result: AsyncResult) => void): void;
参数
要返回的数据结构的类型。 请参阅每个主机支持的强制类型的备注部分。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前选定内容中的数据。 这将以使用 coercionType 参数指定的数据结构或格式返回。 (请参阅备注,了解有关数据强制的详细信息。)
返回
void
注解
要求集:
使用时 (HtmlCoercionOffice.CoercionType.Html)
使用时 (MatrixCoercionOffice.CoercionType.Matrix)
使用时 (OoxmlCoercionOffice.CoercionType.Ooxml)
使用时 (TableCoercionOffice.CoercionType.Table)
使用时 (TextCoercionOffice.CoercionType.Text)
在传递给 getSelectedDataAsync 方法的回调函数中,您可以使用 AsyncResult 对象的属性返回以下信息。
属性 用于...
AsyncResult.value 始终返回 undefined,这是因为没有要检索的对象或数据。
AsyncResult.status 确定操作是成功还是失败。
AsyncResult.error 如果操作失败,则访问提供错误信息的 Error 对象。
AsyncResult.asyncContext 在 AsyncResult 对象中未经改动的返回的任何类型的用户定义项。
主机 支持的 coercionType
Excel、PowerPoint、Project 和 Word `Office.CoercionType.Text` (字符串)
Excel 和 Word `Office.CoercionType.Matrix` (数组的数组)
Excel 和 Word `Office.CoercionType.Table` (TableData 对象)
Word `Office.CoercionType.Html`
Word `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint 网页和 Windows `Office.CoercionType.SlideRange`
Excel、PowerPoint 和 Word `Office.CoercionType.XmlSvg`
getSelectedResourceAsync(options, callback)
仅项目文档。 获取当前选定的资源 ID。
getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是作为字符串的资源的 GUID。
返回
void
getSelectedResourceAsync(callback)
仅项目文档。 获取当前选定的资源 ID。
getSelectedResourceAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getResourceInfo);
});
};
// Get the GUID of the resource and then get the resource fields.
function getResourceInfo() {
getResourceGuid().then(
function (data) {
getResourceFields(data);
}
);
}
// Get the GUID of the selected resource.
function getResourceGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get the specified fields for the selected resource.
function getResourceFields(resourceGuid) {
var targetFields =
[Office.ProjectResourceFields.Name,
Office.ProjectResourceFields.Units,
Office.ProjectResourceFields.BaseCalendar];
var fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
var index = 0;
getField();
// Get each field, and then display the field values in the add-in.
function getField() {
if (index == targetFields.length) {
var output = '';
for (var i = 0; i < fieldValues.length; i++) {
output += fieldValues[i] + '
';
}
$('#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) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是作为字符串的资源的 GUID。
返回
void
getSelectedTaskAsync(callback)
仅项目文档。 获取当前选定的任务 ID。
getSelectedTaskAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getTaskInfo);
});
};
// // Get the GUID of the task, and then get local task properties.
function getTaskInfo() {
getTaskGuid().then(
function (data) {
getTaskProperties(data);
}
);
}
// Get the GUID of the selected task.
function getTaskGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedTaskAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get local properties for the selected task, and then display it in the add-in.
function getTaskProperties(taskGuid) {
Office.context.document.getTaskAsync(
taskGuid,
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var taskInfo = result.value;
var output = String.format(
'Name: {0}
GUID: {1}
SharePoint task ID: {2}
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)
仅项目文档。 获取当前选定的视图类型 (Ex。 甘特图) 视图名称。
getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的属性包含下列属性: - 视图的名称, viewName 作为 ProjectViewTypes 常量。 viewType - 视图的类型,作为 ProjectViewTypes 常量的整数值。
返回
void
getSelectedViewAsync(callback)
仅项目文档。 获取当前选定的视图类型 (Ex。 甘特图) 视图名称。
getSelectedViewAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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:
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
Office.context.document.addHandlerAsync(
Office.EventType.ViewSelectionChanged,
getActiveView);
getActiveView();
});
};
// Get the active view's name and type.
function getActiveView() {
Office.context.document.getSelectedViewAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var output = String.format(
'View name: {0}
View type: {1}',
result.value.viewName, viewType);
$('#message').html(output);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getTaskAsync(taskId, options, callback)
仅项目文档。 获取给定 taskId WSS任务名称、任务 ID 和 ResourceNames。
getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性包含以下属性: taskName - 任务的名称。 wssTaskId - 同步的 SharePoint 任务列表中任务的 ID。 如果项目未与 SharePoint 任务列表同步,则值为 0。 resourceNames - 分配给任务的资源名称的逗号分隔列表。
返回
void
getTaskAsync(taskId, callback)
仅项目文档。 获取给定 taskId WSS任务名称、任务 ID 和 ResourceNames。
getTaskAsync(taskId: string, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getTaskInfo);
});
};
// Get the GUID of the task, and then get local task properties.
function getTaskInfo() {
getTaskGuid().then(
function (data) {
getTaskProperties(data);
}
);
}
// Get the GUID of the selected task.
function getTaskGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedTaskAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get local properties for the selected task, and then display it in the add-in.
function getTaskProperties(taskGuid) {
Office.context.document.getTaskAsync(
taskGuid,
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
var taskInfo = result.value;
var output = String.format(
'Name: {0}
GUID: {1}
SharePoint task ID: {2}
Resource names: {3}',
taskInfo.taskName, taskGuid, taskInfo.wssTaskId, taskInfo.resourceNames);
$('#message').html(output);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getTaskByIndexAsync(taskIndex, options, callback)
仅项目文档。 获取任务集合中具有指定索引的任务的 GUID。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
taskIndex
number
The index of the task in the collection of tasks for the project.
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是字符串形式的任务 GUID。
返回
void
getTaskByIndexAsync(taskIndex, callback)
仅项目文档。 获取任务集合中具有指定索引的任务的 GUID。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult) => void): void;
参数
taskIndex
number
The index of the task in the collection of tasks for the project.
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
var taskGuids = ;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#get-info').click(getTaskInfo);
});
};
// Get the maximum task index, and then get the task GUIDs.
function getTaskInfo() {
getMaxTaskIndex().then(
function (data) {
getTaskGuids(data);
}
);
}
// Get the maximum index of the tasks for the current project.
function getMaxTaskIndex() {
var defer = $.Deferred();
Office.context.document.getMaxTaskIndexAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get each task GUID, and then display the GUIDs in the add-in.
function getTaskGuids(maxTaskIndex) {
var defer = $.Deferred();
for (var i = 0; i <= maxTaskIndex; i++) {
getTaskGuid(i);
}
return defer.promise();
function getTaskGuid(index) {
Office.context.document.getTaskByIndexAsync(index,
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
taskGuids.push(result.value);
if (index == maxTaskIndex) {
defer.resolve();
$('#message').html(taskGuids.toString());
}
}
else {
onError(result.error);
}
}
);
}
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();
getTaskFieldAsync(taskId, fieldId, options, callback)
仅项目文档。 获取提供的任务 ID 的任务域。 (Ex. StartDate) 。
getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
fieldId
number
任务域。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性包含 fieldValue 属性,它表示指定字段的值。
返回
void
getTaskFieldAsync(taskId, fieldId, callback)
仅项目文档。 获取提供的任务 ID 的任务域。 (Ex. StartDate) 。
getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
fieldId
number
任务域。
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
$('#get-info').click(getTaskInfo);
});
};
// Get the GUID of the task, and then get the task fields.
function getTaskInfo() {
getTaskGuid().then(
function (data) {
getTaskFields(data);
}
);
}
// Get the GUID of the selected task.
function getTaskGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedTaskAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Get the specified fields for the selected task.
function getTaskFields(taskGuid) {
var output = '';
var targetFields = [Office.ProjectTaskFields.Priority, Office.ProjectTaskFields.PercentComplete];
var fieldValues = ['Priority: ', '% Complete: '];
var index = 0;
getField();
// Get each field, and then display the field values in the add-in.
function getField() {
if (index == targetFields.length) {
for (var i = 0; i < fieldValues.length; i++) {
output += fieldValues[i] + '
';
}
$('#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) => void): void;
参数
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性包含以下属性: listName - 同步的 SharePoint 任务列表的名称。 serverUrl - 同步的 SharePoint 任务列表的 URL。
返回
void
getWSSUrlAsync(callback)
仅项目文档。 获取WSS列表的 URL 和列表名称,MPP 也同步。
getWSSUrlAsync(callback?: (result: AsyncResult) => void): void;
参数
callback
(result: Office.AsyncResult) => 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) => void): void;
参数
id
string | number
要转到的对象或位置的标识符。
要转到的位置类型。
提供是否选择导航到的位置的选项。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前视图。
返回
void
注解
PowerPoint 不支持母版视图中的 goToByIdAsync 方法。
selectionMode 选项导致的行为因主机而异:
在 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) => void): void;
参数
id
string | number
要转到的对象或位置的标识符。
要转到的位置类型。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. value结果的 属性是当前视图。
返回
void
注解
PowerPoint 不支持母版视图中的 goToByIdAsync 方法。
selectionMode 选项导致的行为因主机而异:
在 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.
var firstSlideId = 0;
function gotoSelectedSlide() {
//Get currently selected slide's id
Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange, function (asyncResult) {
if (asyncResult.status == "failed") {
app.showNotification("Action failed with error: " + asyncResult.error.message);
}
else {
firstSlideId = asyncResult.value.slides[0].id;
app.showNotification(JSON.stringify(asyncResult.value));
}
});
//Go to slide by id.
Office.context.document.goToByIdAsync(firstSlideId, Office.GoToType.Slide, function (asyncResult) {
if (asyncResult.status == "failed") {
app.showNotification("Action failed with error: " + asyncResult.error.message);
}
else {
app.showNotification("Navigation successful");
}
});
}
// Go to slide by index (PowerPoint)
// The following example shows how to:
// 1. Specify the index of the first, last, previous, or next slide to go to.
// 2. Pass an anonymous callback function that returns the status of the operation
// to the callback parameter of the goToByIdAsync method.
// 3. Display the value on the add-in's page.
function goToSlideByIndex() {
var goToFirst = Office.Index.First;
var goToLast = Office.Index.Last;
var goToPrevious = Office.Index.Previous;
var goToNext = Office.Index.Next;
Office.context.document.goToByIdAsync(goToNext, Office.GoToType.Index, function (asyncResult) {
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else {
showMessage("Navigation successful");
}
});
}
removeHandlerAsync(eventType, options, callback)
删除指定事件类型的事件处理程序。
removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void;
参数
事件类型。 对于文档,可以是"Document.SelectionChanged"或"Document.ActiveViewChanged"。
提供用于确定要删除的事件处理程序的选项。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
注解
removeHandlerAsync(eventType, callback)
删除指定事件类型的事件处理程序。
removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void;
参数
事件类型。 对于文档,可以是"Document.SelectionChanged"或"Document.ActiveViewChanged"。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
注解
示例
// 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
Office.context.document.addHandlerAsync(
Office.EventType.ResourceSelectionChanged,
getResourceGuid);
$('#remove-handler').click(removeEventHandler);
});
};
// Remove the event handler.
function removeEventHandler() {
Office.context.document.removeHandlerAsync(
Office.EventType.ResourceSelectionChanged,
{handler:getResourceGuid,
asyncContext:'The handler is removed.'},
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
$('#remove-handler').attr('disabled', 'disabled');
$('#message').html(result.asyncContext);
}
}
);
}
// Get the GUID of the currently selected resource and display it in the add-in.
function getResourceGuid() {
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
$('#message').html('Resource GUID: ' + result.value);
}
}
);
}
function onError(error) {
$('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}
})();
setResourceFieldAsync(resourceId, fieldId, fieldValue, options, callback)
仅项目文档。 设置指定资源 ID 的资源域。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
resourceId
string
资源 ID 的字符串或值。
fieldId
number
资源域。
fieldValue
string | number | boolean | object
目标字段的值。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)
仅项目文档。 设置指定资源 ID 的资源域。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void;
参数
resourceId
string
资源 ID 的字符串或值。
fieldId
number
资源域。
fieldValue
string | number | boolean | object
目标字段的值。
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#set-info').click(setResourceInfo);
});
};
// Get the GUID of the resource, and then get the resource fields.
function setResourceInfo() {
getResourceGuid().then(
function (data) {
setResourceFields(data);
}
);
}
// Get the GUID of the selected resource.
function getResourceGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedResourceAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Set the specified fields for the selected resource.
function setResourceFields(resourceGuid) {
var targetFields = [Office.ProjectResourceFields.StandardRate, Office.ProjectResourceFields.Notes];
var fieldValues = [.28, 'Notes for the resource.'];
// Set the field value. If the call is successful, set the next field.
for (var i = 0; i < targetFields.length; i++) {
Office.context.document.setResourceFieldAsync(
resourceGuid,
targetFields[i],
fieldValues[i],
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
i++;
}
else {
onError(result.error);
}
}
);
}
$('#message').html('Field values set');
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();
setSelectedDataAsync(data, options, callback)
将指定数据写入当前所选内容。
setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => 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 中,还可以将数据指定为包含有效公式的数组数组,以将其添加到选定单元格。 例如,如果没有覆盖其他数据,将数据设置为 [ [ "=SUM (A1:A5) ","=AVERAGE (A1:A5) "将添加 ] 这两个公式到所选内容。 ] 与在单个单元格上将公式设置为“text”一样,设置后你将无法读取添加的公式(或任何已有公式),只能读取公式的结果。
TableData 对象: 将插入带标题的表格。 在 Excel 中,如果在为 data 参数传递的 TableData 对象中指定公式,则由于 Excel 的"计算列"功能自动复制列中的公式,可能无法获得预期的结果。 若要在想要将包含公式的公式写入选定表格时,请尝试将数据指定为数组 (而不是 TableData 对象) 的数组,并指定 data coercionType 为 Microsoft.Office.Matrix 或"matrix"。 但是,此技术将仅在满足以下条件之一时阻止"计算列"功能: (1) 您写入列的所有单元格,或 (2) 列中已至少有两个不同的公式。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. AsyncResult.value 属性始终返回 undefined,因为没有要检索的对象或数据。
返回
void
注解
要求集:
HtmlCoercion, (时选择 Office.CoercionType.Html)
ImageCoercion 1.1 (使用时 Office.CoercionType.Image)
使用时 (MatrixCoercionOffice.CoercionType.Matrix)
使用时 (OoxmlCoercionOffice.CoercionType.Ooxml)
使用时 (TableCoercionOffice.CoercionType.Table)
使用时 (TextCoercionOffice.CoercionType.Text)
ImageCoercion 1.2 (使用时 Office.CoercionType.XmlSvg)
特定于应用程序的行为
将数据写入选定内容时,应用以下特定于应用程序的操作。
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` 为字符串,则指定文本作为当前单元格的值插入。
如果 为数组的数组 ("matrix") ,则插入指定的行和列集(如果周围单元格中不会覆盖任何其他 `data` 数据)。
如果为 TableData 对象,则插入一个新的 Excel 表,该表包含一组指定的行和标题(如果周围单元格中不会覆盖任何其他 `data` 数据)。
如果选择了多个单元格 If the shape does not match the shape of `data`,则返回错误。
If the shape of the selection exactly matches the shape of `data`,则所选单元格的值将基于 `data`.
插入图像 插入的图像为浮动图像。 imageLeft 和 imageTop 位置参数是相对于当前选定的单元格而言的。 允许 imageLeft 和 imageTop 的值为负数,将由 Excel 重新调整在工作表内放置的图像位置。 除非 imageWidth 和 imageHeight 参数均已提供,否则将锁定图像的纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。
所有其他情况 返回错误。
Excel 网页版 除了上面为 Excel 描述的行为之外,这些限制还适用于在 Excel 网页中写入数据时 一次调用此方法时,可以使用 参数写入工作表的单元格总数不能超过 `data` 20,000。
传递给参数的格式设置组的数量 `cellFormat` 不能超过 100。 每个格式设置组由应用于特定单元格范围的一组格式组成。
PowerPoint 插入图像 插入的图像为浮动图像。 imageLeft 和 imageTop 位置参数是可选的,但如果提供,应同时存在这两个参数。 如果提供单个值,则它将被忽略。 允许 imageLeft 和 imageTop 的值为负数,且可以将图像放置在幻灯片的外部。 如果未给定任何可选参数,并且幻灯片有一个占位符,则图像将替换幻灯片中的占位符。 除非 imageWidth和 imageHeight 参数均已提供,否则将锁定图像纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。
Hosts
主机 支持的 coercionType
Excel、PowerPoint、Project 和 Word `Office.CoercionType.Text` (字符串)
Excel 和 Word `Office.CoercionType.Matrix` (数组的数组)
Excel 和 Word `Office.CoercionType.Table` (TableData 对象)
Word `Office.CoercionType.Html`
Word `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint 网页和 Windows `Office.CoercionType.SlideRange`
Excel、PowerPoint 和 Word `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) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed){
write(error.name + ": " + error.message);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
// Specifying the optional coercionType parameter lets you specify the kind of data you want to write
// to a selection. The following example writes data as an array of three rows of two columns,
// specifying the coercionType as `Matrix` for that data structure, and if that fails,
// displays the value of the error.message property.
function writeMatrix() {
Office.context.document.setSelectedDataAsync(
[["Red", "Rojo"], ["Green", "Verde"], ["Blue", "Azul"]],
{coercionType: Office.CoercionType.Matrix}
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed){
write(error.name + ": " + error.message);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
// The following example writes data as a one column table with a header and four rows,
// specifying the coercionType as `Table` for that data structure, and if that fails,
// displays the value of the error.message property.
function writeTable() {
// Build table.
var myTable = new Office.TableData();
myTable.headers = [["Cities"]];
myTable.rows = [['Berlin'], ['Roma'], ['Tokyo'], ['Seattle']];
// Write table.
Office.context.document.setSelectedDataAsync(myTable, {coercionType: Office.CoercionType.Table},
function (result) {
var error = result.error
if (result.status === Office.AsyncResultStatus.Failed) {
write(error.name + ": " + error.message);
}
});
}
// Function that writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
// In Word if you want to write HTML to the selection, you can specify the coercionType parameter as `Html`
// as shown in the following example, which uses HTML tags to make "Hello" bold.
function writeHtmlData() {
Office.context.document.setSelectedDataAsync(
"Hello 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;
参数
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 中,还可以将数据指定为包含有效公式的数组数组,以将其添加到选定单元格。 例如,如果没有覆盖其他数据,将数据设置为 [ [ "=SUM (A1:A5) ","=AVERAGE (A1:A5) "将添加 ] 这两个公式到所选内容。 ] 与在单个单元格上将公式设置为“text”一样,设置后你将无法读取添加的公式(或任何已有公式),只能读取公式的结果。
TableData 对象: 将插入带标题的表格。 在 Excel 中,如果在为 data 参数传递的 TableData 对象中指定公式,则由于 Excel 的"计算列"功能自动复制列中的公式,可能无法获得预期的结果。 若要在想要将包含公式的公式写入选定表格时,请尝试将数据指定为数组 (而不是 TableData 对象) 的数组,并指定 data coercionType 为 Microsoft.Office.Matrix 或"matrix"。 但是,此技术将仅在满足以下条件之一时阻止"计算列"功能: (1) 您写入列的所有单元格,或 (2) 列中已至少有两个不同的公式。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult. AsyncResult.value 属性始终返回 undefined,因为没有要检索的对象或数据。
返回
void
注解
要求集:
HtmlCoercion, (时选择 Office.CoercionType.Html)
使用时 (ImageCoercionOffice.CoercionType.Image)
使用时 (MatrixCoercionOffice.CoercionType.Matrix)
使用时 (OoxmlCoercionOffice.CoercionType.Ooxml)
使用时 (TableCoercionOffice.CoercionType.Table)
使用时 (TextCoercionOffice.CoercionType.Text)
ImageCoercion 1.2 (使用时 Office.CoercionType.XmlSvg)
特定于应用程序的行为
将数据写入选定内容时,应用以下特定于应用程序的操作。
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` 为字符串,则指定文本作为当前单元格的值插入。
如果 为数组的数组 ("matrix") ,则插入指定的行和列集(如果周围单元格中不会覆盖任何其他 `data` 数据)。
如果为 TableData 对象,则插入一个新的 Excel 表,该表包含一组指定的行和标题(如果周围单元格中不会覆盖任何其他 `data` 数据)。
如果选择了多个单元格If the shape does not match the shape of `data`,则返回错误。
If the shape of the selection exactly matches the shape of `data`,则所选单元格的值将基于 `data`.
插入图像 插入的图像为浮动图像。 imageLeft 和 imageTop 位置参数是相对于当前选定的单元格而言的。 允许 imageLeft 和 imageTop 的值为负数,将由 Excel 重新调整在工作表内放置的图像位置。 除非 imageWidth 和 imageHeight 参数均已提供,否则将锁定图像的纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。
所有其他情况 返回错误。
Excel 网页版 除了上面为 Excel 描述的行为之外,这些限制还适用于在 Excel 网页中写入数据时 一次调用此方法时,可以使用 参数写入工作表的单元格总数不能超过 `data` 20,000。
传递给参数的格式设置组的数量 `cellFormat` 不能超过 100。 每个格式设置组由应用于特定单元格范围的一组格式组成。
PowerPoint 插入图像 插入的图像为浮动图像。 imageLeft 和 imageTop 位置参数是可选的,但如果提供,应同时存在这两个参数。 如果提供单个值,则它将被忽略。 允许 imageLeft 和 imageTop 的值为负数,且可以将图像放置在幻灯片的外部。 如果未给定任何可选参数,并且幻灯片有一个占位符,则图像将替换幻灯片中的占位符。 除非 imageWidth和 imageHeight 参数均已提供,否则将锁定图像纵横比。 如果只给定 imageWidth 参数或只给定 imageHeight 参数,则另一个值将自动扩展以保留原始纵横比。
Hosts
主机 支持的 coercionType
Excel、PowerPoint、Project 和 Word `Office.CoercionType.Text` (字符串)
Excel 和 Word `Office.CoercionType.Matrix` (数组的数组)
Excel 和 Word `Office.CoercionType.Table` (TableData 对象)
Word `Office.CoercionType.Html`
Word `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint 网页和 Windows `Office.CoercionType.SlideRange`
Excel、PowerPoint 和 Word `Office.CoercionType.XmlSvg`
setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)
仅项目文档。 设置指定任务 ID 的任务域。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
fieldId
number
任务域。
fieldValue
string | number | boolean | object
目标字段的值。
提供一个选项,用于保留任何类型的未更改的上下文数据,以用于回调。
callback
(result: Office.AsyncResult) => void
可选。 回调返回时调用的函数,其唯一的参数的类型为 Office.AsyncResult.
返回
void
setTaskFieldAsync(taskId, fieldId, fieldValue, callback)
仅项目文档。 设置指定任务 ID 的任务域。
重要 提示:此 API 仅适用于 Windows 桌面上的 Project 2016。
setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void;
参数
taskId
string
任务 ID 的字符串或值。
fieldId
number
任务域。
fieldValue
string | number | boolean | object
目标字段的值。
callback
(result: Office.AsyncResult) => 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:
//
//
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// After the DOM is loaded, add-in-specific code can run.
app.initialize();
$('#set-info').click(setTaskInfo);
});
};
// Get the GUID of the task, and then get the task fields.
function setTaskInfo() {
getTaskGuid().then(
function (data) {
setTaskFields(data);
}
);
}
// Get the GUID of the selected task.
function getTaskGuid() {
var defer = $.Deferred();
Office.context.document.getSelectedTaskAsync(
function (result) {
if (result.status === Office.AsyncResultStatus.Failed) {
onError(result.error);
}
else {
defer.resolve(result.value);
}
}
);
return defer.promise();
}
// Set the specified fields for the selected task.
function setTaskFields(taskGuid) {
var targetFields = [Office.ProjectTaskFields.Active, Office.ProjectTaskFields.Notes];
var fieldValues = [true, 'Notes for the task.'];
// Set the field value. If the call is successful, set the next field.
for (var i = 0; i < targetFields.length; i++) {
Office.context.document.setTaskFieldAsync(
taskGuid,
targetFields[i],
fieldValues[i],
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
i++;
}
else {
onError(result.error);
}
}
);
}
$('#message').html('Field values set');
}
function onError(error) {
app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
}
})();