Word.Document class

Document 对象是顶层对象。 Document 对象包含一个或多个节、内容控件以及包含文档内容的正文。

Extends

注解

[ API 集:WordApi 1.1 ]

属性

body

获取main文档的正文对象。 正文是排除页眉、页脚、脚注、文本框等的文本。

changeTrackingMode

指定 ChangeTracking 模式。

contentControls

获取文档中的内容控件对象的集合。 这包括文档正文中的内容控件、页眉、页脚、文本框等。

context

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

customXmlParts

获取文档中的自定义 XML 部件。

properties

获取文档的属性。

saved

指示是否已保存在文档中所做的更改。 如果值为 true,表示文档自上次保存以来并未更改。

sections

获取文档中节对象的集合。

settings

获取文档中加载项的设置。

方法

addStyle(name, type)

按名称和类型向文档中添加样式。

addStyle(name, typeString)

按名称和类型向文档中添加样式。

close(closeBehavior)

关闭当前文档。

close(closeBehaviorString)

关闭当前文档。

compare(filePath, documentCompareOptions)

显示修订标记,以表明指定的文档与另一个文档的区别。

deleteBookmark(name)

从文档中删除书签(如果存在)。

getAnnotationById(id)

按 ID 获取批注。 ItemNotFound如果未找到批注,则引发错误。

getBookmarkRange(name)

获取书签的范围。 ItemNotFound如果书签不存在,则引发错误。

getBookmarkRangeOrNullObject(name)

获取书签的范围。 如果书签不存在,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性

getContentControls(options)

获取文档中当前支持的内容控件。

getEndnoteBody()

获取单个正文中的文档尾注。

getFootnoteBody()

获取单个正文中的文档脚注。

getParagraphByUniqueLocalId(id)

按其唯一本地 ID 获取段落。 ItemNotFound如果集合为空,则引发错误。

getSelection()

获取文档的当前选定内容。 不支持多个选择。

getStyles()

获取一个 StyleCollection 对象,该对象代表文档的整个样式集。

importStylesFromJson(stylesJson)

从 JSON 格式的字符串导入样式。

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

使用其他属性将文档插入到目标文档中的特定位置。 默认情况下会复制页眉、页脚、水印和其他节属性。

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

save(saveBehavior, fileName)

保存文档。

save(saveBehaviorString, fileName)

保存文档。

search(searchText, searchOptions)

对整个文档的范围使用指定的搜索选项执行搜索。 搜索结果是 range 对象的集合。

set(properties, options)

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

set(properties)

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

toJSON()

重写 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 JSON.stringify (,反过来又调用toJSON传递给它的 对象的 方法。) 而原始Word。Document 对象是一个 API 对象,toJSON该方法返回一个纯 JavaScript 对象, (类型为 Word.Interfaces.DocumentData) ,其中包含原始对象中加载的任何子属性的浅表副本。

track()

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

untrack()

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

事件

onAnnotationClicked

当用户单击批注 (或使用 Alt+Down) 进行选择时发生。

onAnnotationHovered

当用户将光标悬停在批注上时发生。

onAnnotationInserted

当用户添加一个或多个注释时发生。

onAnnotationPopupAction

当用户在批注弹出菜单中执行操作时发生。

onAnnotationRemoved

当用户删除一个或多个批注时发生。

onContentControlAdded

在添加内容控件时发生。 在处理程序中运行 context.sync () 以获取新内容控件的属性。

onParagraphAdded

当用户添加新段落时发生。

onParagraphChanged

当用户更改段落时发生。

onParagraphDeleted

当用户删除段落时发生。

属性详细信息

body

获取main文档的正文对象。 正文是排除页眉、页脚、脚注、文本框等的文本。

readonly body: Word.Body;

属性值

注解

[ API 集:WordApi 1.1 ]

changeTrackingMode

指定 ChangeTracking 模式。

changeTrackingMode: Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly";

属性值

Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly"

注解

[ API 集:WordApi 1.4 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-change-tracking.yaml

// Gets the current change tracking mode.
await Word.run(async (context) => {
  const document = context.document;
  document.load("changeTrackingMode");
  await context.sync();

  if (document.changeTrackingMode === Word.ChangeTrackingMode.trackMineOnly) {
    console.log("Only my changes are being tracked.");
  } else if (document.changeTrackingMode === Word.ChangeTrackingMode.trackAll) {
    console.log("Everyone's changes are being tracked.");
  } else {
    console.log("No changes are being tracked.");
  }
});

contentControls

获取文档中的内容控件对象的集合。 这包括文档正文中的内容控件、页眉、页脚、文本框等。

readonly contentControls: Word.ContentControlCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

context

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

context: RequestContext;

属性值

customXmlParts

获取文档中的自定义 XML 部件。

readonly customXmlParts: Word.CustomXmlPartCollection;

属性值

注解

[ API 集:WordApi 1.4 ]

properties

获取文档的属性。

readonly properties: Word.DocumentProperties;

属性值

注解

[ API 集:WordApi 1.3 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/30-properties/get-built-in-properties.yaml

await Word.run(async (context) => {
    const builtInProperties = context.document.properties;
    builtInProperties.load("*"); // Let's get all!

    await context.sync();
    console.log(JSON.stringify(builtInProperties, null, 4));
});

saved

指示是否已保存在文档中所做的更改。 如果值为 true,表示文档自上次保存以来并未更改。

readonly saved: boolean;

属性值

boolean

注解

[ API 集:WordApi 1.1 ]

sections

获取文档中节对象的集合。

readonly sections: Word.SectionCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

settings

获取文档中加载项的设置。

readonly settings: Word.SettingCollection;

属性值

注解

[ API 集:WordApi 1.4 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-settings.yaml

// Gets all custom settings this add-in set on this document.
await Word.run(async (context) => {
  const settings = context.document.settings;
  settings.load("items");
  await context.sync();

  if (settings.items.length == 0) {
    console.log("There are no settings.");
  } else {
    console.log("All settings:");
    for (let i = 0; i < settings.items.length; i++) {
      console.log(settings.items[i]);
    }
  }
});

方法详细信息

addStyle(name, type)

按名称和类型向文档中添加样式。

addStyle(name: string, type: Word.StyleType): Word.Style;

参数

name

string

必填。 表示样式名称的字符串。

type
Word.StyleType

必填。 样式类型,包括字符、列表、段落或表格。

返回

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Adds a new style.
await Word.run(async (context) => {
  const newStyleName = $("#new-style-name").val() as string;
  if (newStyleName == "") {
    console.warn("Enter a style name to add.");
    return;
  }

  const style = context.document.getStyles().getByNameOrNullObject(newStyleName);
  style.load();
  await context.sync();

  if (!style.isNullObject) {
    console.warn(
      `There's an existing style with the same name '${newStyleName}'! Please provide another style name.`
    );
    return;
  }

  const newStyleType = ($("#new-style-type").val() as unknown) as Word.StyleType;
  context.document.addStyle(newStyleName, newStyleType);
  await context.sync();
  
  console.log(newStyleName + " has been added to the style list.");
});

addStyle(name, typeString)

按名称和类型向文档中添加样式。

addStyle(name: string, typeString: "Character" | "List" | "Paragraph" | "Table"): Word.Style;

参数

name

string

必填。 表示样式名称的字符串。

typeString

"Character" | "List" | "Paragraph" | "Table"

必填。 样式类型,包括字符、列表、段落或表格。

返回

注解

[ API 集:WordApi 1.5 ]

close(closeBehavior)

关闭当前文档。

close(closeBehavior?: Word.CloseBehavior): void;

参数

closeBehavior
Word.CloseBehavior

可选。 关闭行为必须为“保存”或“SkipSave”。 默认值为“Save”。

返回

void

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/save-close.yaml

// Closes the document with default behavior
// for current state of the document.
await Word.run(async (context) => {
  context.document.close();
});

close(closeBehaviorString)

关闭当前文档。

close(closeBehaviorString?: "Save" | "SkipSave"): void;

参数

closeBehaviorString

"Save" | "SkipSave"

可选。 关闭行为必须为“保存”或“SkipSave”。 默认值为“Save”。

返回

void

注解

[ API 集:WordApi 1.5 ]

compare(filePath, documentCompareOptions)

注意

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

显示修订标记,以表明指定的文档与另一个文档的区别。

compare(filePath: string, documentCompareOptions?: Word.DocumentCompareOptions): void;

参数

filePath

string

必填。 与指定文档进行比较的文档的路径。

documentCompareOptions
Word.DocumentCompareOptions

可选。 指定比较文档行为的其他选项。

返回

void

注解

[ API 集:WordApi BETA (仅预览版) ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/compare-documents.yaml

// Compares the current document with a specified external document.
await Word.run(async (context) => {
  // Absolute path of an online or local document.
  const filePath = $("#filePath")
    .val()
    .toString();
  // Options that configure the compare operation.
  const options = {
    compareTarget: Word.CompareTarget.compareTargetCurrent,
    detectFormatChanges: false
    // Other options you choose...
    };
  context.document.compare(filePath, options);

  await context.sync();

  console.log("Differences shown in the current document.");
});

deleteBookmark(name)

从文档中删除书签(如果存在)。

deleteBookmark(name: string): void;

参数

name

string

必填。 不区分大小写的书签名称。

返回

void

注解

[ API 集:WordApi 1.4 ]

getAnnotationById(id)

按 ID 获取批注。 ItemNotFound如果未找到批注,则引发错误。

getAnnotationById(id: string): Word.Annotation;

参数

id

string

要获取的批注的 ID。

返回

注解

[ API 集:WordApi 1.7 ]

getBookmarkRange(name)

获取书签的范围。 ItemNotFound如果书签不存在,则引发错误。

getBookmarkRange(name: string): Word.Range;

参数

name

string

必填。 不区分大小写的书签名称。

返回

注解

[ API 集:WordApi 1.4 ]

getBookmarkRangeOrNullObject(name)

获取书签的范围。 如果书签不存在,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性

getBookmarkRangeOrNullObject(name: string): Word.Range;

参数

name

string

必填。 不区分大小写的书签名称。

返回

注解

[ API 集:WordApi 1.4 ]

getContentControls(options)

获取文档中当前支持的内容控件。

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

参数

options
Word.ContentControlOptions

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

返回

注解

[ API 集:WordApi 1.5 ]

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

示例

// 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 on all checkbox content controls.
await Word.run(async (context) => {
  let contentControls = context.document.getContentControls({
    types: [Word.ContentControlType.checkBox]
  });
  contentControls.load("items");

  await context.sync();

  const length = contentControls.items.length;
  console.log(`Number of checkbox content controls: ${length}`);

  if (length <= 0) {
    return;
  }

  const checkboxContentControls = [];
  for (let i = 0; i < length; i++) {
    let contentControl = contentControls.items[i];
    contentControl.load("id,checkboxContentControl/isChecked");
    checkboxContentControls.push(contentControl);
  }

  await context.sync();

  console.log("isChecked state before:");
  const updatedCheckboxContentControls = [];
  for (let i = 0; i < checkboxContentControls.length; i++) {
    const currentCheckboxContentControl = checkboxContentControls[i];
    const isCheckedBefore = currentCheckboxContentControl.checkboxContentControl.isChecked;
    console.log(`id: ${currentCheckboxContentControl.id} ... isChecked: ${isCheckedBefore}`);

    currentCheckboxContentControl.checkboxContentControl.isChecked = !isCheckedBefore;
    currentCheckboxContentControl.load("id,checkboxContentControl/isChecked");
    updatedCheckboxContentControls.push(currentCheckboxContentControl);
  }

  await context.sync();

  console.log("isChecked state after:");
  for (let i = 0; i < updatedCheckboxContentControls.length; i++) {
    const currentCheckboxContentControl = updatedCheckboxContentControls[i];
    console.log(
      `id: ${currentCheckboxContentControl.id} ... isChecked: ${currentCheckboxContentControl.checkboxContentControl.isChecked}`
    );
  }
});

getEndnoteBody()

获取单个正文中的文档尾注。

getEndnoteBody(): Word.Body;

返回

注解

[ API 集:WordApi 1.5 ]

getFootnoteBody()

获取单个正文中的文档脚注。

getFootnoteBody(): Word.Body;

返回

注解

[ API 集:WordApi 1.5 ]

getParagraphByUniqueLocalId(id)

按其唯一本地 ID 获取段落。 ItemNotFound如果集合为空,则引发错误。

getParagraphByUniqueLocalId(id: string): Word.Paragraph;

参数

id

string

必填。 标准 8-4-4-4-4-12 GUID 格式的唯一本地 ID,不带大括号。 请注意,ID 因会话和共同创作者而异。

返回

注解

[ API 集:WordApi 1.6 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

await Word.run(async (context) => {
  const paragraphId = $("#paragraph-id").val() as string;
  const paragraph = context.document.getParagraphByUniqueLocalId(paragraphId);
  paragraph.load();
  await paragraph.context.sync();

  console.log(paragraph);
});

getSelection()

获取文档的当前选定内容。 不支持多个选择。

getSelection(): Word.Range;

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    const textSample = 'This is an example of the insert text method. This is a method ' + 
        'which allows users to insert text into a selection. It can insert text into a ' +
        'relative location or it can overwrite the current selection. Since the ' +
        'getSelection method returns a range object, look up the range object documentation ' +
        'for everything you can do with a selection.';
    
    // Create a range proxy object for the current selection.
    const range = context.document.getSelection();
    
    // Queue a command to insert text at the end of the selection.
    range.insertText(textSample, Word.InsertLocation.end);
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted the text at the end of the selection.');
});  

getStyles()

获取一个 StyleCollection 对象,该对象代表文档的整个样式集。

getStyles(): Word.StyleCollection;

返回

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Gets the number of styles.
await Word.run(async (context) => {
  const styles = context.document.getStyles();
  const count = styles.getCount();
  await context.sync();

  console.log(`Number of styles: ${count.value}`);
});

importStylesFromJson(stylesJson)

从 JSON 格式的字符串导入样式。

importStylesFromJson(stylesJson: string): OfficeExtension.ClientResult<string[]>;

参数

stylesJson

string

必填。 表示样式的 JSON 格式字符串。

返回

注解

[ API 集:WordApi 1.6 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/manage-custom-style.yaml

// Imports styles from JSON.
await Word.run(async (context) => {
  const str =
    '{"styles":[{"baseStyle":"Default Paragraph Font","builtIn":false,"inUse":true,"linked":false,"nameLocal":"NewCharStyle","priority":2,"quickStyle":true,"type":"Character","unhideWhenUsed":false,"visibility":false,"paragraphFormat":null,"font":{"name":"DengXian Light","size":16.0,"bold":true,"italic":false,"color":"#F1A983","underline":"None","subscript":false,"superscript":true,"strikeThrough":true,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#FF0000"}},{"baseStyle":"Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewParaStyle","nameLocal":"NewParaStyle","priority":1,"quickStyle":true,"type":"Paragraph","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Centered","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":72.0,"lineSpacing":18.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":72.0,"spaceAfter":30.0,"spaceBefore":30.0,"widowControl":true},"font":{"name":"DengXian","size":14.0,"bold":true,"italic":true,"color":"#8DD873","underline":"Single","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":true,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#00FF00"}},{"baseStyle":"Table Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewTableStyle","nameLocal":"NewTableStyle","priority":100,"type":"Table","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Left","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":0.0,"lineSpacing":12.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":0.0,"spaceAfter":0.0,"spaceBefore":0.0,"widowControl":true},"font":{"name":"DengXian","size":20.0,"bold":false,"italic":true,"color":"#D86DCB","underline":"None","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"tableStyle":{"allowBreakAcrossPage":true,"alignment":"Left","bottomCellMargin":0.0,"leftCellMargin":0.08,"rightCellMargin":0.08,"topCellMargin":0.0,"cellSpacing":0.0},"shading":{"backgroundPatternColor":"#60CAF3"}}]}';
  const styles = context.document.importStylesFromJson(str);
  await context.sync();
  console.log("Styles imported from JSON:", styles);
});

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

使用其他属性将文档插入到目标文档中的特定位置。 默认情况下会复制页眉、页脚、水印和其他节属性。

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

参数

base64File

string

必填。 .docx 文件的 Base64 编码内容。

insertLocation

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

必填。 该值必须为“Replace”、“Start”或“End”。

insertFileOptions
Word.InsertFileOptions

可选。 应导入到目标文档的其他属性。

返回

注解

[ API 集:WordApi 1.5 ]

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

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-external-document.yaml

// Inserts content (applying selected settings) from another document passed in as a Base64-encoded string.
await Word.run(async (context) => {
  // Use the Base64-encoded string representation of the selected .docx file.
  context.document.insertFileFromBase64(externalDocument, "Replace", {
    importTheme: true,
    importStyles: true,
    importParagraphSpacing: true,
    importPageColor: true,
    importChangeTrackingMode: true,
    importCustomProperties: true,
    importCustomXmlParts: true,
    importDifferentOddEvenPages: true
  });
  await context.sync();
});

load(options)

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

load(options?: Word.Interfaces.DocumentLoadOptions): Word.Document;

参数

options
Word.Interfaces.DocumentLoadOptions

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

返回

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;
    
    // Queue a command to load content control properties.
    thisDocument.load('contentControls/id, contentControls/text, contentControls/tag');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (thisDocument.contentControls.items.length !== 0) {
        for (let i = 0; i < thisDocument.contentControls.items.length; i++) {
            console.log(thisDocument.contentControls.items[i].id);
            console.log(thisDocument.contentControls.items[i].text);
            console.log(thisDocument.contentControls.items[i].tag);
        }
    } else {
        console.log('No content controls in this document.');
    }
});

load(propertyNames)

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

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

参数

propertyNames

string | string[]

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

返回

load(propertyNamesAndPaths)

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

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

参数

propertyNamesAndPaths

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

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

返回

save(saveBehavior, fileName)

保存文档。

save(saveBehavior?: Word.SaveBehavior, fileName?: string): void;

参数

saveBehavior
Word.SaveBehavior

可选。 保存行为必须为“保存”或“提示”。 默认值为“Save”。

fileName

string

可选。 文件名 (排除文件扩展名) 。 仅对新文档生效。

返回

void

注解

[ API 集:WordApi 1.1 ]

注意: saveBehaviorfileName 参数是在 WordApi 1.5 中引入的。

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;

    // Queue a command to load the document save state (on the saved property).
    thisDocument.load('saved');    
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (thisDocument.saved === false) {
        // Queue a command to save this document.
        thisDocument.save();
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Saved the document');
    } else {
        console.log('The document has not changed since the last save.');
    }
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/save-close.yaml

// Saves the document with default behavior
// for current state of the document.
await Word.run(async (context) => {
  context.document.save();
  await context.sync();
});

save(saveBehaviorString, fileName)

保存文档。

save(saveBehaviorString?: "Save" | "Prompt", fileName?: string): void;

参数

saveBehaviorString

"Save" | "Prompt"

可选。 保存行为必须为“保存”或“提示”。 默认值为“Save”。

fileName

string

可选。 文件名 (排除文件扩展名) 。 仅对新文档生效。

返回

void

注解

[ API 集:WordApi 1.1 ]

注意: saveBehaviorfileName 参数是在 WordApi 1.5 中引入的。

search(searchText, searchOptions)

对整个文档的范围使用指定的搜索选项执行搜索。 搜索结果是 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.7 ]

set(properties, options)

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

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

参数

properties
Word.Interfaces.DocumentUpdateData

一个 JavaScript 对象,其属性按同构方式构造为调用方法的对象的属性。

options
OfficeExtension.UpdateOptions

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

返回

void

set(properties)

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

set(properties: Word.Document): void;

参数

properties
Word.Document

返回

void

toJSON()

重写 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 JSON.stringify (,反过来又调用toJSON传递给它的 对象的 方法。) 而原始Word。Document 对象是一个 API 对象,toJSON该方法返回一个纯 JavaScript 对象, (类型为 Word.Interfaces.DocumentData) ,其中包含原始对象中加载的任何子属性的浅表副本。

toJSON(): Word.Interfaces.DocumentData;

返回

track()

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

track(): Word.Document;

返回

untrack()

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

untrack(): Word.Document;

返回

事件详细信息

onAnnotationClicked

当用户单击批注 (或使用 Alt+Down) 进行选择时发生。

readonly onAnnotationClicked: OfficeExtension.EventHandlers<Word.AnnotationClickedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.7 ]

onAnnotationHovered

当用户将光标悬停在批注上时发生。

readonly onAnnotationHovered: OfficeExtension.EventHandlers<Word.AnnotationHoveredEventArgs>;

事件类型

注解

[ API 集:WordApi 1.7 ]

onAnnotationInserted

当用户添加一个或多个注释时发生。

readonly onAnnotationInserted: OfficeExtension.EventHandlers<Word.AnnotationInsertedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.7 ]

onAnnotationPopupAction

注意

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

当用户在批注弹出菜单中执行操作时发生。

readonly onAnnotationPopupAction: OfficeExtension.EventHandlers<Word.AnnotationPopupActionEventArgs>;

事件类型

注解

[ API 集:WordApi BETA (仅预览版) ]

onAnnotationRemoved

当用户删除一个或多个批注时发生。

readonly onAnnotationRemoved: OfficeExtension.EventHandlers<Word.AnnotationRemovedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.7 ]

onContentControlAdded

在添加内容控件时发生。 在处理程序中运行 context.sync () 以获取新内容控件的属性。

readonly onContentControlAdded: OfficeExtension.EventHandlers<Word.ContentControlAddedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

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

// Registers the onAdded event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onContentControlAdded.add(contentControlAdded);
  await context.sync();

  console.log("Added event handler for when content controls are added.");
});

...

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

onParagraphAdded

当用户添加新段落时发生。

readonly onParagraphAdded: OfficeExtension.EventHandlers<Word.ParagraphAddedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.6 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

// Registers the onParagraphAdded event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphAdded.add(paragraphAdded);
  await context.sync();

  console.log("Added event handler for when paragraphs are added.");
});

...

async function paragraphAdded(event: Word.ParagraphAddedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were added:`, event.uniqueLocalIds);
  });
}

onParagraphChanged

当用户更改段落时发生。

readonly onParagraphChanged: OfficeExtension.EventHandlers<Word.ParagraphChangedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.6 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onchanged-event.yaml

// Registers the onParagraphChanged event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphChanged.add(paragraphChanged);
  await context.sync();

  console.log("Added event handler for when content is changed in paragraphs.");
});

...

async function paragraphChanged(event: Word.ParagraphChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs where content was changed:`, event.uniqueLocalIds);
  });
}

onParagraphDeleted

当用户删除段落时发生。

readonly onParagraphDeleted: OfficeExtension.EventHandlers<Word.ParagraphDeletedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.6 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/ondeleted-event.yaml

// Registers the onParagraphDeleted event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphDeleted.add(paragraphDeleted);
  await context.sync();

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

...

async function paragraphDeleted(event: Word.ParagraphDeletedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were deleted:`, event.uniqueLocalIds);
  });
}