Word.ContentControl class

表示内容控件。 内容控件是文档中绑定的、有可能添加标签的区域,它们充当特定类型的内容的容器。 各个内容控件可能包含诸如图像、表格或格式化文本段落等内容。 目前仅支持格式文本、纯文本、复选框、下拉列表和组合框内容控件。

扩展

注解

API 集:WordApi 1.1

使用方

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;

    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'color,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' +
            '   ----- appearance: ' + contentControls.items[0].appearance +
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});

属性

appearance

指定内容控件的外观。 值可以是 boundingBoxtagshidden

buildingBlockGalleryContentControl

如果内容控件为 Word,则获取与构建基块库相关的数据。ContentControlType is buildingBlockGallery. 情况并非 null 如此。

cannotDelete

指定用户是否可以删除内容控件。 与 removeWhenEdited互斥。

cannotEdit

指定用户是否可以编辑内容控件的内容。

checkboxContentControl

获取内容控件的数据(当其类型为 checkBox时)。 情况并非 null 如此。

color

指定内容控件的颜色。 颜色以“#RRGGBB”格式或使用颜色名称指定。

comboBoxContentControl

获取内容控件的数据(当其类型为 comboBox时)。 情况并非 null 如此。

contentControls

获取内容控件中的对象集合 ContentControl

context

与对象关联的请求上下文。 这将加载项的进程连接到 Office 主机应用程序的进程。

datePickerContentControl

如果内容控件为 Word,则获取日期选取器相关数据。ContentControlType is datePicker. 情况并非 null 如此。

dropDownListContentControl

获取内容控件的数据(当其类型为 dropDownList时)。 情况并非 null 如此。

endnotes

获取内容控件中的尾注集合。

fields

获取内容控件中的对象集合 Field

font

获取内容控件的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。

footnotes

获取内容控件中的脚注集合。

groupContentControl

如果内容控件为 Word,则获取与组相关的数据。ContentControlType is group. 情况并非 null 如此。

id

获取表示内容控件标识符的整数。

inlinePictures

获取内容控件中的对象集合 InlinePicture 。 该集合不包括浮动图像。

lists

获取内容控件中的对象集合 List

paragraphs

获取内容控件中的对象集合 Paragraph

parentBody

获取 contentControl 的父正文。

parentContentControl

获取包含此内容控件的内容控件。 如果没有父内容控件,则引发 ItemNotFound 错误。

parentContentControlOrNullObject

获取包含此内容控件的内容控件。 如果没有父内容控件,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

parentTable

获取包含 contentControl 的 table。 如果表中未包含,则引发 ItemNotFound 错误。

parentTableCell

获取包含 contentControl 的 tableCell。 如果表单元格中未包含错误,则引发 ItemNotFound 错误。

parentTableCellOrNullObject

获取包含 contentControl 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

parentTableOrNullObject

获取包含 contentControl 的 table。 如果它未包含在表中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

pictureContentControl

如果是内容控件的 Word,则获取与图片相关的数据。ContentControlType is picture. 情况并非 null 如此。

placeholderText

指定内容控件的占位符文本。 内容控件为空时,将显示灰色的文本。

removeWhenEdited

指定是否在编辑内容控件后将其删除。 与 cannotDelete互斥。

repeatingSectionContentControl

如果是内容控件的 Word,则获取与重复节相关的数据。ContentControlType is repeatingSection. 情况并非 null 如此。

style

指定内容控件的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可在区域设置之间移植的内置样式,请参阅 styleBuiltIn 属性。

styleBuiltIn

指定内容控件的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 要使用自定义样式或本地化样式名称,请参阅 style 属性。

subtype

获取 contentControl 的子类型。 子类型可以是 richTextInlinerichTextParagraphsrichTextTableCellrichTextTableRowrichTextTable以及格式文本内容控件,plainTextParagraphplainTextInline对于纯文本内容控件,checkBox对于复选框内容控件,dropDownList对于下拉列表内容控件,comboBox对于组合框内容控件,对于构建基块库内容控件datePickerbuildingBlockGallery对于日期选取器内容控件,repeatingSection对于重复节内容控件,picture对于图片内容控件group,对于组内容控件。

tables

获取内容控件中的对象集合 Table

tag

指定用于标识内容控件的标记。

text

获取内容控件的文本。

title

指定内容控件的标题。

type

获取内容控件的类型。 目前仅支持富文本、纯文本、检查框、下拉列表、组合框、构建基块库、日期选取器、重复节、图片和组内容控件。

xmlMapping

返回一个 XmlMapping 对象,该对象表示内容控件到文档数据存储中 XML 数据的映射。

方法

clear()

清除内容控件的内容。 用户可以对已清除的内容执行撤消操作。

delete(keepContent)

删除内容控件及其内容。 如果设置为 true,则keepContent不会删除该内容。

getComments()

获取与内容控件关联的注释。

getContentControls(options)

获取此内容控件中当前支持的子内容控件。

getHtml()

获取对象的 HTML 表示形式 ContentControl 。 在网页或 HTML 查看器中呈现时,格式将与文档的格式非常匹配,但不完全匹配。 此方法不会为不同平台上的同一文档返回完全相同的 HTML, (Windows、Mac、Word Web 等 ) 。 如果需要精确的保真度或跨平台的一致性,请使用 ContentControl.getOoxml() 返回的 XML 并将其转换为 HTML。

getOoxml()

获取对象的 ContentControl Office Open XML (OOXML) 表示形式。

getRange(rangeLocation)

获取整个内容控件或内容控件的起点/终点,作为一个范围。

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取已审阅的文本。

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取已审阅的文本。

getTextRanges(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取内容控件中的文本范围。

getTrackedChanges()

获取内容控件中的对象集合 TrackedChange

insertBreak(breakType, insertLocation)

在主文档的指定位置插入分隔符。 此方法不能与 、 和richTextTableRowrichTextTableCell内容控件一起使用。richTextTable

insertFileFromBase64(base64File, insertLocation)

将文档插入到指定位置的内容控件中。

insertHtml(html, insertLocation)

将 HTML 插入到内容控件中的指定位置。

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

将嵌入式图片插入到内容控件中的指定位置。

insertOoxml(ooxml, insertLocation)

将 OOXML 插入指定位置的内容控件中。

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertTable(rowCount, columnCount, insertLocation, values)

将包含指定行数和列数的 table 插入 contentControl 中或在其旁边插入。

insertText(text, insertLocation)

将文本插入到内容控件中的指定位置。

load(options)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNames)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNamesAndPaths)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

resetState()

重置内容控件的状态。

search(searchText, searchOptions)

使用指定的搜索选项对对象范围执行 ContentControl 搜索。 搜索结果是对象的 Range 集合。

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

set(properties, options)

同时设置对象的多个属性。 可以传递具有相应属性的纯文本对象,也可以传递另一个相同类型的 API 对象。

set(properties)

基于现有加载的对象,同时在对象上设置多个属性。

setState(contentControlState)

设置内容控件的状态。

setState(contentControlState)

设置内容控件的状态。

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将内容控件拆分为各个子范围。

toJSON()

覆盖 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 (JSON.stringify反过来调用 toJSON 传递给它的对象的方法。) 虽然原始 Word.ContentControl 对象是 API 对象, toJSON 但该方法返回一个纯 JavaScript 对象, (类型化为 Word.Interfaces.ContentControlData) ,其中包含从原始对象加载的任何子属性的浅层副本。

track()

根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果在调用中 .sync 使用此对象,并且在“.run”批处理的顺序执行之外使用此对象,并且在设置属性或对对象调用方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将对象添加到跟踪对象集合。 如果此对象是集合的一部分,您还应跟踪父集合。

untrack()

释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 需要在内存释放生效之前调用 context.sync()

活动

onCommentAdded

在添加新批注时发生。

onCommentChanged

更改注释或其回复时发生。

onCommentDeselected

取消选择批注时出现。

onCommentSelected

选中批注时出现。

onDataChanged

当内容控件中的数据更改时发生。 若要获取新文本,请在处理程序中加载此内容控件。 若要获取旧文本,请不要加载它。

onDeleted

在删除内容控件时发生。 请勿在处理程序中加载此内容控件,否则将无法获取其原始属性。

onEntered

在进入内容控件时发生。

onExited

在退出内容控件时发生,例如,当光标离开内容控件时。

onSelectionChanged

当内容控件中的选择发生更改时发生。

属性详细信息

appearance

指定内容控件的外观。 值可以是 boundingBoxtagshidden

appearance: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden";

属性值

Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"

注解

API 集:WordApi 1.1

buildingBlockGalleryContentControl

如果内容控件为 Word,则获取与构建基块库相关的数据。ContentControlType is buildingBlockGallery. 情况并非 null 如此。

readonly buildingBlockGalleryContentControl: Word.BuildingBlockGalleryContentControl;

属性值

注解

API 集:WordApiDesktop 1.3

cannotDelete

指定用户是否可以删除内容控件。 与 removeWhenEdited互斥。

cannotDelete: boolean;

属性值

boolean

注解

API 集:WordApi 1.1

cannotEdit

指定用户是否可以编辑内容控件的内容。

cannotEdit: boolean;

属性值

boolean

注解

API 集:WordApi 1.1

checkboxContentControl

获取内容控件的数据(当其类型为 checkBox时)。 情况并非 null 如此。

readonly checkboxContentControl: Word.CheckboxContentControl;

属性值

注解

API 集:WordApi 1.7

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-checkbox-content-control.yaml

// Toggles the isChecked property of the first checkbox content control found in the selection.
await Word.run(async (context) => {
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.checkBox]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id,checkboxContentControl/isChecked");

  await context.sync();

  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
    parentContentControl.load("id,type,checkboxContentControl/isChecked");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
      console.warn("No checkbox content control is currently selected.");
      return;
    } else {
      selectedContentControl = parentContentControl;
    }
  }

  const isCheckedBefore = selectedContentControl.checkboxContentControl.isChecked;
  console.log("isChecked state before:", `id: ${selectedContentControl.id} ... isChecked: ${isCheckedBefore}`);
  selectedContentControl.checkboxContentControl.isChecked = !isCheckedBefore;
  selectedContentControl.load("id,checkboxContentControl/isChecked");
  await context.sync();

  console.log(
    "isChecked state after:",
    `id: ${selectedContentControl.id} ... isChecked: ${selectedContentControl.checkboxContentControl.isChecked}`
  );
});

color

指定内容控件的颜色。 颜色以“#RRGGBB”格式或使用颜色名称指定。

color: string;

属性值

string

注解

API 集:WordApi 1.1

comboBoxContentControl

获取内容控件的数据(当其类型为 comboBox时)。 情况并非 null 如此。

readonly comboBoxContentControl: Word.ComboBoxContentControl;

属性值

注解

API 集:WordApi 1.9

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-combo-box-content-control.yaml

// Adds the provided list item to the first combo box content control in the selection.
await Word.run(async (context) => {
  const listItemText = (document.getElementById("item-to-add") as HTMLInputElement).value.trim();
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.comboBox]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id,comboBoxContentControl");
  await context.sync();

  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
    parentContentControl.load("id,type,comboBoxContentControl");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.comboBox) {
      console.warn("No combo box content control is currently selected.");
      return;
    } else {
      selectedContentControl = parentContentControl;
    }
  }

  selectedContentControl.comboBoxContentControl.addListItem(listItemText);
  await context.sync();

  console.log(`List item added to control with ID ${selectedContentControl.id}: ${listItemText}`);
});

contentControls

获取内容控件中的对象集合 ContentControl

readonly contentControls: Word.ContentControlCollection;

属性值

注解

API 集:WordApi 1.1

context

与对象关联的请求上下文。 这将加载项的进程连接到 Office 主机应用程序的进程。

context: RequestContext;

属性值

datePickerContentControl

如果内容控件为 Word,则获取日期选取器相关数据。ContentControlType is datePicker. 情况并非 null 如此。

readonly datePickerContentControl: Word.DatePickerContentControl;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-date-picker-content-control.yaml

// Gets and logs the properties of the first date picker content control.
await Word.run(async (context) => {
  let contentControls = context.document.getContentControls({
    types: [Word.ContentControlType.datePicker]
  });
  contentControls.load("items");

  await context.sync();

  if (contentControls.items.length === 0) {
    console.warn("No date picker content controls found in the document.");
    return;
  }

  const firstControl = contentControls.items[0];
  firstControl.load("datePickerContentControl");

  await context.sync();

  const datePicker: Word.DatePickerContentControl = firstControl.datePickerContentControl;
  datePicker.load("dateCalendarType, dateDisplayFormat, dateDisplayLocale, dateStorageFormat");

  await context.sync();

  console.log("Date picker content control properties:");
  console.log("  Calendar type: " + datePicker.dateCalendarType);
  console.log("  Display format: " + datePicker.dateDisplayFormat);
  console.log("  Display locale: " + datePicker.dateDisplayLocale);
  console.log("  Storage format: " + datePicker.dateStorageFormat);
});

dropDownListContentControl

获取内容控件的数据(当其类型为 dropDownList时)。 情况并非 null 如此。

readonly dropDownListContentControl: Word.DropDownListContentControl;

属性值

注解

API 集:WordApi 1.9

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-dropdown-list-content-control.yaml

// Adds the provided list item to the first dropdown list content control in the selection.
await Word.run(async (context) => {
  const listItemText = (document.getElementById("item-to-add") as HTMLInputElement).value.trim();
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.dropDownList]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id,dropDownListContentControl");
  await context.sync();

  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
    parentContentControl.load("id,type,dropDownListContentControl");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.dropDownList) {
      console.warn("No dropdown list content control is currently selected.");
      return;
    } else {
      selectedContentControl = parentContentControl;
    }
  }

  selectedContentControl.dropDownListContentControl.addListItem(listItemText);
  await context.sync();

  console.log(`List item added to control with ID ${selectedContentControl.id}: ${listItemText}`);
});

endnotes

获取内容控件中的尾注集合。

readonly endnotes: Word.NoteItemCollection;

属性值

注解

API 集:WordApi 1.5

fields

获取内容控件中的对象集合 Field

readonly fields: Word.FieldCollection;

属性值

注解

API 集:WordApi 1.4

font

获取内容控件的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。

readonly font: Word.Font;

属性值

注解

API 集:WordApi 1.1

footnotes

获取内容控件中的脚注集合。

readonly footnotes: Word.NoteItemCollection;

属性值

注解

API 集:WordApi 1.5

groupContentControl

如果内容控件为 Word,则获取与组相关的数据。ContentControlType is group. 情况并非 null 如此。

readonly groupContentControl: Word.GroupContentControl;

属性值

注解

API 集:WordApiDesktop 1.3

id

获取表示内容控件标识符的整数。

readonly id: number;

属性值

number

注解

API 集:WordApi 1.1

inlinePictures

获取内容控件中的对象集合 InlinePicture 。 该集合不包括浮动图像。

readonly inlinePictures: Word.InlinePictureCollection;

属性值

注解

API 集:WordApi 1.1

lists

获取内容控件中的对象集合 List

readonly lists: Word.ListCollection;

属性值

注解

API 集:WordApi 1.3

paragraphs

获取内容控件中的对象集合 Paragraph

readonly paragraphs: Word.ParagraphCollection;

属性值

注解

API 集:WordApi 1.1

重要提示: 对于要求集 1.1 和 1.2,不会返回完全包含在此内容控件中的表中的段落。 从要求集1.3中,还返回此类表中的段落。

parentBody

获取 contentControl 的父正文。

readonly parentBody: Word.Body;

属性值

注解

API 集:WordApi 1.3

parentContentControl

获取包含此内容控件的内容控件。 如果没有父内容控件,则引发 ItemNotFound 错误。

readonly parentContentControl: Word.ContentControl;

属性值

注解

API 集:WordApi 1.1

parentContentControlOrNullObject

获取包含此内容控件的内容控件。 如果没有父内容控件,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentContentControlOrNullObject: Word.ContentControl;

属性值

注解

API 集:WordApi 1.3

parentTable

获取包含 contentControl 的 table。 如果表中未包含,则引发 ItemNotFound 错误。

readonly parentTable: Word.Table;

属性值

注解

API 集:WordApi 1.3

parentTableCell

获取包含 contentControl 的 tableCell。 如果表单元格中未包含错误,则引发 ItemNotFound 错误。

readonly parentTableCell: Word.TableCell;

属性值

注解

API 集:WordApi 1.3

parentTableCellOrNullObject

获取包含 contentControl 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentTableCellOrNullObject: Word.TableCell;

属性值

注解

API 集:WordApi 1.3

parentTableOrNullObject

获取包含 contentControl 的 table。 如果它未包含在表中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentTableOrNullObject: Word.Table;

属性值

注解

API 集:WordApi 1.3

pictureContentControl

如果是内容控件的 Word,则获取与图片相关的数据。ContentControlType is picture. 情况并非 null 如此。

readonly pictureContentControl: Word.PictureContentControl;

属性值

注解

API 集:WordApiDesktop 1.3

placeholderText

指定内容控件的占位符文本。 内容控件为空时,将显示灰色的文本。

placeholderText: string;

属性值

string

注解

API 集:WordApi 1.1

removeWhenEdited

指定是否在编辑内容控件后将其删除。 与 cannotDelete互斥。

removeWhenEdited: boolean;

属性值

boolean

注解

API 集:WordApi 1.1

repeatingSectionContentControl

如果是内容控件的 Word,则获取与重复节相关的数据。ContentControlType is repeatingSection. 情况并非 null 如此。

readonly repeatingSectionContentControl: Word.RepeatingSectionContentControl;

属性值

注解

API 集:WordApiDesktop 1.3

style

指定内容控件的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可在区域设置之间移植的内置样式,请参阅 styleBuiltIn 属性。

style: string;

属性值

string

注解

API 集:WordApi 1.1

styleBuiltIn

指定内容控件的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 要使用自定义样式或本地化样式名称,请参阅 style 属性。

styleBuiltIn: Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6";

属性值

Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6"

注解

API 集:WordApi 1.3

subtype

获取 contentControl 的子类型。 子类型可以是 richTextInlinerichTextParagraphsrichTextTableCellrichTextTableRowrichTextTable以及格式文本内容控件,plainTextParagraphplainTextInline对于纯文本内容控件,checkBox对于复选框内容控件,dropDownList对于下拉列表内容控件,comboBox对于组合框内容控件,对于构建基块库内容控件datePickerbuildingBlockGallery对于日期选取器内容控件,repeatingSection对于重复节内容控件,picture对于图片内容控件group,对于组内容控件。

readonly subtype: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText" | "Group";

属性值

Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText" | "Group"

注解

API 集:WordApi 1.3

tables

获取内容控件中的对象集合 Table

readonly tables: Word.TableCollection;

属性值

注解

API 集:WordApi 1.3

tag

指定用于标识内容控件的标记。

tag: string;

属性值

string

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Traverses each paragraph of the document and wraps a content control on each with either a even or odd tags.
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none"); // Don't need any properties; just wrap each paragraph with a content control.

  await context.sync();

  for (let i = 0; i < paragraphs.items.length; i++) {
    let contentControl = paragraphs.items[i].insertContentControl();
    // For even, tag "even".
    if (i % 2 === 0) {
      contentControl.tag = "even";
    } else {
      contentControl.tag = "odd";
    }
  }
  console.log("Content controls inserted: " + paragraphs.items.length);

  await context.sync();
});

text

获取内容控件的文本。

readonly text: string;

属性值

string

注解

API 集:WordApi 1.1

title

指定内容控件的标题。

title: string;

属性值

string

注解

API 集:WordApi 1.1

type

获取内容控件的类型。 目前仅支持富文本、纯文本、检查框、下拉列表、组合框、构建基块库、日期选取器、重复节、图片和组内容控件。

readonly type: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText" | "Group";

属性值

Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText" | "Group"

注解

API 集:WordApi 1.1

xmlMapping

返回一个 XmlMapping 对象,该对象表示内容控件到文档数据存储中 XML 数据的映射。

readonly xmlMapping: Word.XmlMapping;

属性值

注解

API 集:WordApiDesktop 1.3

方法详细信息

clear()

清除内容控件的内容。 用户可以对已清除的内容执行撤消操作。

clear(): void;

返回

void

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the content controls collection.
    contentControls.load('text');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (contentControls.items.length === 0) {
        console.log("There isn't a content control in this document.");
    } else {
        // Queue a command to clear the contents of the first content control.
        contentControls.items[0].clear();

        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control cleared of contents.');
    }
});

delete(keepContent)

删除内容控件及其内容。 如果设置为 true,则keepContent不会删除该内容。

delete(keepContent: boolean): void;

参数

keepContent

boolean

指示是否应使用内容控件删除内容。 如果设置为 true,则keepContent不会删除该内容。

返回

void

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondeleted-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls.getByTag("forTesting");
  contentControls.load("items");
  await context.sync();

  if (contentControls.items.length === 0) {
    console.log("There are no content controls in this document.");
  } else {
    console.log("Control to be deleted:", contentControls.items[0]);
    contentControls.items[0].delete(false);
    await context.sync();
  }
});

getComments()

获取与内容控件关联的注释。

getComments(): Word.CommentCollection;

返回

注解

API 集:WordApi 1.4

getContentControls(options)

获取此内容控件中当前支持的子内容控件。

getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;

参数

options
Word.ContentControlOptions

可选。 用于定义返回哪些内容控件的选项。

返回

注解

API 集:WordApi 1.5

重要提示: 如果在 options 参数中提供了特定类型,则仅返回受支持类型的内容控件。 请注意,使用通用 Word 的方法将引发异常与特定类型无关的 ContentControl。 随着时间的推移,可能会支持其他类型的内容控件。 因此,加载项应请求和处理特定类型的内容控件。

getHtml()

获取对象的 HTML 表示形式 ContentControl 。 在网页或 HTML 查看器中呈现时,格式将与文档的格式非常匹配,但不完全匹配。 此方法不会为不同平台上的同一文档返回完全相同的 HTML, (Windows、Mac、Word Web 等 ) 。 如果需要精确的保真度或跨平台的一致性,请使用 ContentControl.getOoxml() 返回的 XML 并将其转换为 HTML。

getHtml(): OfficeExtension.ClientResult<string>;

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection that contains a specific tag.
    const contentControlsWithTag = context.document.contentControls.getByTag('Customer-Address');
    
    // Queue a command to load the tag property for all of content controls.
    contentControlsWithTag.load('tag');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControlsWithTag.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the HTML contents of the first content control.
        const html = contentControlsWithTag.items[0].getHtml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control HTML: ' + html.value);
    }
});

getOoxml()

获取对象的 ContentControl Office Open XML (OOXML) 表示形式。

getOoxml(): OfficeExtension.ClientResult<string>;

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the OOXML contents of the first content control.
        const ooxml = contentControls.items[0].getOoxml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control OOXML: ' + ooxml.value);
    }
});

getRange(rangeLocation)

获取整个内容控件或内容控件的起点/终点,作为一个范围。

getRange(rangeLocation?: Word.RangeLocation | "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range;

参数

rangeLocation

Word.RangeLocation | "Whole" | "Start" | "End" | "Before" | "After" | "Content"

可选。 范围位置必须为 wholestartafterbeforeend 或 。content

返回

注解

API 集:WordApi 1.3

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取已审阅的文本。

getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;

参数

changeTrackingVersion
Word.ChangeTrackingVersion

可选。 值必须为 OR 。originalcurrent 默认值为 current

返回

注解

API 集:WordApi 1.4

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取已审阅的文本。

getReviewedText(changeTrackingVersion?: "Original" | "Current"): OfficeExtension.ClientResult<string>;

参数

changeTrackingVersion

"Original" | "Current"

可选。 值必须为 OR 。originalcurrent 默认值为 current

返回

注解

API 集:WordApi 1.4

getTextRanges(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取内容控件中的文本范围。

getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;

参数

endingMarks

string[]

标点符号和其他结束标记为字符串数组。

trimSpacing

boolean

可选。 指示是否从范围集合中返回的范围的开头和结尾) 剪裁空格、制表符、分栏符和段落结束标记 (空格字符。 默认值指示 false 范围开头和结尾的空格字符包含在范围集合中。

返回

注解

API 集:WordApi 1.3

getTrackedChanges()

获取内容控件中的对象集合 TrackedChange

getTrackedChanges(): Word.TrackedChangeCollection;

返回

注解

API 集:WordApi 1.6

insertBreak(breakType, insertLocation)

在主文档的指定位置插入分隔符。 此方法不能与 、 和richTextTableRowrichTextTableCell内容控件一起使用。richTextTable

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After"): void;

参数

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

休息类型。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

值必须为 startend、、before或 。after

返回

void

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of content controls.
    contentControls.load('id');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    // We now will have access to the content control collection.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a page break after the first content control.
        contentControls.items[0].insertBreak(Word.BreakType.page, Word.InsertLocation.after);
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a page break after the first content control.');    
    }
});

insertFileFromBase64(base64File, insertLocation)

将文档插入到指定位置的内容控件中。

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

base64File

string

.docx 文件的 Base64 编码内容。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

值必须为 replacestart、或 endreplace不能与 和richTextTableRow内容控件一起使用richTextTable

返回

注解

API 集:WordApi 1.1

如果要插入的文档包含 ActiveX 控件,则不支持插入, (可能在表单字段) 中。 请考虑将此类窗体字段替换为适合你的场景的内容控件或其他选项。

insertHtml(html, insertLocation)

将 HTML 插入到内容控件中的指定位置。

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

html

string

要插入到内容控件中的 HTML。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

值必须为 replacestart、或 endreplace不能与 和richTextTableRow内容控件一起使用richTextTable

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put HTML into the contents of the first content control.
        contentControls.items[0].insertHtml(
            '<strong>HTML content inserted into the content control.</strong>',
            'Start');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted HTML in the first content control.');
    }
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

将嵌入式图片插入到内容控件中的指定位置。

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.InlinePicture;

参数

base64EncodedImage

string

要插入内容控件中的 Base64 编码图像。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

值必须为 replacestart、或 endreplace不能与 和richTextTableRow内容控件一起使用richTextTable

返回

注解

API 集:WordApi 1.2

insertOoxml(ooxml, insertLocation)

将 OOXML 插入指定位置的内容控件中。

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

ooxml

string

要插入到内容控件的 OOXML。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

值必须为 replacestart、或 endreplace不能与 和richTextTableRow内容控件一起使用richTextTable

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put OOXML into the contents of the first content control.
        contentControls.items[0].insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", "End");
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted OOXML in the first content control.');
    }
});  

// Read "Create better add-ins for Word with Office Open XML" for guidance on working with OOXML.
// https://learn.microsoft.com/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After"): Word.Paragraph;

参数

paragraphText

string

要插入的段落文本。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

值必须为 startend、、before或 。after before并且after不能与 、 和richTextTableRowrichTextTableCell内容控件一起使用。richTextTable

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a paragraph after the first content control.
        contentControls.items[0].insertParagraph('Text of the inserted paragraph.', 'After');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a paragraph after the first content control.');
    }
});  

insertTable(rowCount, columnCount, insertLocation, values)

将包含指定行数和列数的 table 插入 contentControl 中或在其旁边插入。

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After", values?: string[][]): Word.Table;

参数

rowCount

number

表格的行数。

columnCount

number

表格的列数。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

值必须为 startend、、before或 。after before并且after不能与 、 和richTextTableRowrichTextTableCell内容控件一起使用。richTextTable

values

string[][]

可选的二维数组。 如果指定数组中的对应字符串,则填充单元格。

返回

注解

API 集:WordApi 1.3

insertText(text, insertLocation)

将文本插入到内容控件中的指定位置。

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

text

string

要插入到内容控件中的文本。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

值必须为 replacestart、或 endreplace不能与 和richTextTableRow内容控件一起使用richTextTable

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to replace text in the first content control.
        contentControls.items[0].insertText('Replaced text in the first content control.', 'Replace');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Replaced text in the first content control.');
    }
});  

// The Silly stories add-in sample shows how to use the insertText method.
// https://aka.ms/sillystorywordaddin

load(options)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(options?: Word.Interfaces.ContentControlLoadOptions): Word.ContentControl;

参数

options
Word.Interfaces.ContentControlLoadOptions

为要加载的对象属性提供选项。

返回

示例

// Load all of the content control properties
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    } else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');             
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' + 
            '   ----- appearance: ' + contentControls.items[0].appearance + 
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});  

load(propertyNames)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNames?: string | string[]): Word.ContentControl;

参数

propertyNames

string | string[]

指定要加载的属性的逗号分隔的字符串或字符串数组。

返回

load(propertyNamesAndPaths)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.ContentControl;

参数

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select 是指定要加载的属性的逗号分隔字符串,以及 propertyNamesAndPaths.expand 指定要加载的导航属性的逗号分隔字符串。

返回

resetState()

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

重置内容控件的状态。

resetState(): void;

返回

void

注解

API 集:WordApi BETA (仅预览版)

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/insert-and-change-content-controls.yaml

// Resets the state of the first content control.
await Word.run(async (context) => {
  let firstContentControl = context.document.contentControls.getFirstOrNullObject();
  await context.sync();

  if (firstContentControl.isNullObject) {
    console.warn("There are no content controls in this document.");
    return;
  }

  firstContentControl.resetState();
  firstContentControl.load("id");
  await context.sync();

  console.log(`Reset state of first content control with ID: ${firstContentControl.id}`);
});

search(searchText, searchOptions)

使用指定的搜索选项对对象范围执行 ContentControl 搜索。 搜索结果是对象的 Range 集合。

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

参数

searchText

string

搜索文本。

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

可选。 用于搜索的选项。

返回

注解

API 集:WordApi 1.1

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to select the first content control.
        contentControls.items[0].select();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Selected the first content control.');
    }
});  

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionMode?: Word.SelectionMode): void;

参数

selectionMode
Word.SelectionMode

可选。 选择模式必须为 select、 、startend select 为默认值。

返回

void

注解

API 集:WordApi 1.1

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionMode?: "Select" | "Start" | "End"): void;

参数

selectionMode

"Select" | "Start" | "End"

可选。 选择模式必须为 select、 、startend select 为默认值。

返回

void

注解

API 集:WordApi 1.1

set(properties, options)

同时设置对象的多个属性。 可以传递具有相应属性的纯文本对象,也可以传递另一个相同类型的 API 对象。

set(properties: Interfaces.ContentControlUpdateData, options?: OfficeExtension.UpdateOptions): void;

参数

properties
Word.Interfaces.ContentControlUpdateData

一个 JavaScript 对象,其属性与调用该方法的对象的属性同构结构。

options
OfficeExtension.UpdateOptions

提供一个选项,用于在 properties 对象尝试设置任何只读属性时禁止错误。

返回

void

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Adds title and colors to odd and even content controls and changes their appearance.
await Word.run(async (context) => {
  // Get the complete sentence (as range) associated with the insertion point.
  let evenContentControls = context.document.contentControls.getByTag("even");
  let oddContentControls = context.document.contentControls.getByTag("odd");
  evenContentControls.load("length");
  oddContentControls.load("length");

  await context.sync();

  for (let i = 0; i < evenContentControls.items.length; i++) {
    // Change a few properties and append a paragraph.
    evenContentControls.items[i].set({
      color: "red",
      title: "Odd ContentControl #" + (i + 1),
      appearance: Word.ContentControlAppearance.tags
    });
    evenContentControls.items[i].insertParagraph("This is an odd content control", "End");
  }

  for (let j = 0; j < oddContentControls.items.length; j++) {
    // Change a few properties and append a paragraph.
    oddContentControls.items[j].set({
      color: "green",
      title: "Even ContentControl #" + (j + 1),
      appearance: "Tags"
    });
    oddContentControls.items[j].insertHtml("This is an <b>even</b> content control", "End");
  }

  await context.sync();
});

set(properties)

基于现有加载的对象,同时在对象上设置多个属性。

set(properties: Word.ContentControl): void;

参数

properties
Word.ContentControl

返回

void

setState(contentControlState)

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

设置内容控件的状态。

setState(contentControlState: Word.ContentControlState): void;

参数

contentControlState
Word.ContentControlState

要设置的状态。

返回

void

注解

API 集:WordApi BETA (仅预览版)

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/insert-and-change-content-controls.yaml

// Sets the state of the first content control.
await Word.run(async (context) => {
  const state = ((document.getElementById("state-to-set") as HTMLSelectElement)
    .value as unknown) as Word.ContentControlState;
  let firstContentControl = context.document.contentControls.getFirstOrNullObject();
  await context.sync();

  if (firstContentControl.isNullObject) {
    console.warn("There are no content controls in this document.");
    return;
  }

  firstContentControl.setState(state);
  firstContentControl.load("id");
  await context.sync();

  console.log(`Set state of first content control with ID ${firstContentControl.id} to ${state}.`);
});

setState(contentControlState)

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

设置内容控件的状态。

setState(contentControlState: "Error" | "Warning"): void;

参数

contentControlState

"Error" | "Warning"

要设置的状态。

返回

void

注解

API 集:WordApi BETA (仅预览版)

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将内容控件拆分为各个子范围。

split(delimiters: string[], multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;

参数

delimiters

string[]

字符串数组形式的分隔符。

multiParagraphs

boolean

可选。 指示返回的子区域是否可以涵盖多个段落。 默认值为 false which 指示段落边界也用作分隔符。

trimDelimiters

boolean

可选。 指示是否从范围集合中的范围剪裁分隔符。 默认值指示 false 分隔符包含在范围集合中返回的范围中。

trimSpacing

boolean

可选。 指示是否从范围集合中返回的范围的开头和结尾) 剪裁空格、制表符、分栏符和段落结束标记 (空格字符。 默认值指示 false 范围开头和结尾的空格字符包含在范围集合中。

返回

注解

API 集:WordApi 1.3

toJSON()

覆盖 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 (JSON.stringify反过来调用 toJSON 传递给它的对象的方法。) 虽然原始 Word.ContentControl 对象是 API 对象, toJSON 但该方法返回一个纯 JavaScript 对象, (类型化为 Word.Interfaces.ContentControlData) ,其中包含从原始对象加载的任何子属性的浅层副本。

toJSON(): Word.Interfaces.ContentControlData;

返回

track()

根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果在调用中 .sync 使用此对象,并且在“.run”批处理的顺序执行之外使用此对象,并且在设置属性或对对象调用方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将对象添加到跟踪对象集合。 如果此对象是集合的一部分,您还应跟踪父集合。

track(): Word.ContentControl;

返回

untrack()

释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 需要在内存释放生效之前调用 context.sync()

untrack(): Word.ContentControl;

返回

事件详细信息

onCommentAdded

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

在添加新批注时发生。

readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentChanged

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

更改注释或其回复时发生。

readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentDeselected

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

取消选择批注时出现。

readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentSelected

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

选中批注时出现。

readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

API 集:WordApi BETA (仅预览版)

onDataChanged

当内容控件中的数据更改时发生。 若要获取新文本,请在处理程序中加载此内容控件。 若要获取旧文本,请不要加载它。

readonly onDataChanged: OfficeExtension.EventHandlers<Word.ContentControlDataChangedEventArgs>;

事件类型

注解

API 集:WordApi 1.5

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondatachanged-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onDataChanged event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onDataChanged.add(contentControlDataChanged);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when data is changed in content controls.");
  }
});

...

async function contentControlDataChanged(event: Word.ContentControlDataChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls where data was changed:`, event.ids);
  });
}

onDeleted

在删除内容控件时发生。 请勿在处理程序中加载此内容控件,否则将无法获取其原始属性。

readonly onDeleted: OfficeExtension.EventHandlers<Word.ContentControlDeletedEventArgs>;

事件类型

注解

API 集:WordApi 1.5

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondeleted-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onDeleted event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onDeleted.add(contentControlDeleted);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when content controls are deleted.");
  }
});

...

async function contentControlDeleted(event: Word.ContentControlDeletedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls that were deleted:`, event.ids);
  });
}

onEntered

在进入内容控件时发生。

readonly onEntered: OfficeExtension.EventHandlers<Word.ContentControlEnteredEventArgs>;

事件类型

注解

API 集:WordApi 1.5

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onentered-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onEntered event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onEntered.add(contentControlEntered);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when the cursor is placed in content controls.");
  }
});

...

async function contentControlEntered(event: Word.ContentControlEnteredEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. ID of content control that was entered: ${event.ids[0]}`);
  });
}

onExited

在退出内容控件时发生,例如,当光标离开内容控件时。

readonly onExited: OfficeExtension.EventHandlers<Word.ContentControlExitedEventArgs>;

事件类型

注解

API 集:WordApi 1.5

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onexited-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onExited event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onExited.add(contentControlExited);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when the cursor is removed from within content controls.");
  }
});

...

async function contentControlExited(event: Word.ContentControlExitedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. ID of content control that was exited: ${event.ids[0]}`);
  });
}

onSelectionChanged

当内容控件中的选择发生更改时发生。

readonly onSelectionChanged: OfficeExtension.EventHandlers<Word.ContentControlSelectionChangedEventArgs>;

事件类型

注解

API 集:WordApi 1.5

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onselectionchanged-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onSelectionChanged.add(contentControlSelectionChanged);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when selections are changed in content controls.");
  }
});

...

async function contentControlSelectionChanged(event: Word.ContentControlSelectionChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls where selection was changed:`, event.ids);
  });
}