Word.Body class
表示文档或节的正文。
注解
使用方
- Word.ContentControl: parentBody
- Word.文档: body, getEndnoteBody, getFootnoteBody
- Word.DocumentCreated: 正文
- Word.字段: parentBody
- Word.NoteItem: 正文
- Word.段落:parentBody
- Word.范围:parentBody
- Word.Section: body, getFooter, getHeader
- Word.形状:身体
- Word.表: parentBody
- Word.TableCell: 正文
示例
// Get the body object and read its font size.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body = context.document.body;
body.load("font/size");
await context.sync();
console.log("Font size: " + body.font.size);
});
属性
| content |
获取正文中 RTF 内容控件对象的集合。 |
| context | 与对象关联的请求上下文。 这将加载项的进程连接到 Office 主机应用程序的进程。 |
| endnotes | 获取正文中尾注的集合。 |
| fields | 获取正文中的对象集合 |
| font | 获取正文的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。 |
| footnotes | 获取正文中的脚注集合。 |
| inline |
获取正文中的对象集合 |
| lists | 获取正文中的对象集合 |
| paragraphs | 获取正文中的对象集合 |
| parent |
获取 body 的父正文。 例如,表格单元格 body 的父正文可能是标题。 如果没有父正文,则引发 |
| parent |
获取 body 的父正文。 例如,表格单元格 body 的父正文可能是标题。 如果没有父正文,则此方法将返回其 |
| parent |
获取包含正文的内容控件。 如果没有父内容控件,则引发 |
| parent |
获取包含正文的内容控件。 如果没有父内容控件,则此方法将返回其 |
| parent |
获取 body 的父节。 如果没有父节,则引发 |
| parent |
获取 body 的父节。 如果没有父节,则此方法将返回其 |
| shapes | 获取正文中的对象集合 |
| style | 指定正文的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。 |
| style |
指定正文的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 若要使用自定义样式或本地化样式名称,请参阅“style”属性。 |
| tables | 获取正文中的对象集合 |
| text | 获取正文的文本。 使用 |
| type | 获取 body 的类型。 类型可以是 |
方法
| clear() | 清除对象的内容 |
| get |
获取与正文关联的注释。 |
| get |
获取正文中当前支持的内容控件。 |
| get |
获取对象的 HTML 表示形式 |
| get |
获取对象的 |
| get |
获取整个正文或正文的起点/终点,作为一个范围。 |
| get |
根据 ChangeTrackingVersion 选择获取已审阅的文本。 |
| get |
根据 ChangeTrackingVersion 选择获取已审阅的文本。 |
| get |
获取正文中对象的 |
| insert |
在主文档的指定位置插入分隔符。 |
| insert |
|
| insert |
将文档插入到正文中的指定位置。 要插入的文档的最大大小为 4 MB。 |
| insert |
在指定位置插入 HTML。 |
| insert |
将图片插入到正文中的指定位置。 |
| insert |
在指定位置插入 OOXML。 |
| insert |
在指定位置插入段落。 |
| insert |
插入包含指定行数和列数的 table。 |
| insert |
将文本插入到正文中的指定位置。 |
| load(options) | 将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| load(property |
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| load(property |
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| search(search |
使用指定的搜索选项对对象范围执行 |
| select(selection |
选择正文并在 Word UI 中进行浏览。 |
| select(selection |
选择正文并在 Word UI 中进行浏览。 |
| set(properties, options) | 同时设置对象的多个属性。 可以传递具有相应属性的纯文本对象,也可以传递另一个相同类型的 API 对象。 |
| set(properties) | 基于现有加载的对象,同时在对象上设置多个属性。 |
| toJSON() | 覆盖 JavaScript |
| track() | 根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果在调用中 |
| untrack() | 释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 需要在内存释放生效之前调用 |
事件
| on |
在添加新批注时发生。 |
| on |
更改注释或其回复时发生。 |
| on |
删除注释时发生。 |
| on |
取消选择批注时出现。 |
| on |
选中批注时出现。 |
属性详细信息
contentControls
获取正文中 RTF 内容控件对象的集合。
readonly contentControls: Word.ContentControlCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/manage-watermark.yaml
// Removes the watermark from the document using OOXML.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
context.load(sections);
await context.sync();
const header: Word.Body = sections.items[0].getHeader("Primary");
const contentControls: Word.ContentControlCollection = header.contentControls.getByTitle("myTempCC");
context.load(contentControls);
await context.sync();
if (contentControls.items.length > 0) {
contentControls.items[0].delete(false);
await context.sync();
console.log("Watermark removed successfully using OOXML.");
} else {
console.warn("No watermark found in this document.");
}
});
context
endnotes
获取正文中尾注的集合。
readonly endnotes: Word.NoteItemCollection;
属性值
注解
fields
获取正文中的对象集合 Field 。
readonly fields: Word.FieldCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-fields.yaml
// Gets all fields in the document body.
await Word.run(async (context) => {
const fields: Word.FieldCollection = context.document.body.fields.load("items");
await context.sync();
if (fields.items.length === 0) {
console.log("No fields in this document.");
} else {
fields.load(["code", "result"]);
await context.sync();
for (let i = 0; i < fields.items.length; i++) {
console.log(`Field ${i + 1}'s code: ${fields.items[i].code}`, `Field ${i + 1}'s result: ${JSON.stringify(fields.items[i].result)}`);
}
}
});
font
获取正文的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。
readonly font: Word.Font;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Gets the style and the font size, font name, and font color properties on the body object.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to load font and style information for the document body.
body.load("font/size, font/name, font/color, style");
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
// Show font-related property values on the body object.
const results =
"Font size: " +
body.font.size +
"; Font name: " +
body.font.name +
"; Font color: " +
body.font.color +
"; Body style: " +
body.style;
console.log(results);
});
footnotes
获取正文中的脚注集合。
readonly footnotes: Word.NoteItemCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Gets the footnotes in the document body.
await Word.run(async (context) => {
const footnotes: Word.NoteItemCollection = context.document.body.footnotes;
footnotes.load("length");
await context.sync();
console.log(`Number of footnotes in the document body: ${footnotes.items.length}`);
});
inlinePictures
获取正文中的对象集合 InlinePicture 。 该集合不包括浮动图像。
readonly inlinePictures: Word.InlinePictureCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-get-pictures.yaml
// Gets the first image in the document.
await Word.run(async (context) => {
const firstPicture: Word.InlinePicture = context.document.body.inlinePictures.getFirst();
firstPicture.load("width, height, imageFormat");
await context.sync();
console.log(`Image dimensions: ${firstPicture.width} x ${firstPicture.height}`, `Image format: ${firstPicture.imageFormat}`);
// Get the image encoded as Base64.
const base64 = firstPicture.getBase64ImageSrc();
await context.sync();
console.log(base64.value);
});
lists
获取正文中的对象集合 List 。
readonly lists: Word.ListCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/20-lists/organize-list.yaml
// Gets information about the first list in the document.
await Word.run(async (context) => {
const lists: Word.ListCollection = context.document.body.lists;
lists.load("items");
await context.sync();
if (lists.items.length === 0) {
console.warn("There are no lists in this document.");
return;
}
// Get the first list.
const list: Word.List = lists.getFirst();
list.load("levelTypes,levelExistences");
await context.sync();
const levelTypes = list.levelTypes;
console.log("Level types of the first list:");
for (let i = 0; i < levelTypes.length; i++) {
console.log(`- Level ${i + 1} (index ${i}): ${levelTypes[i]}`);
}
const levelExistences = list.levelExistences;
console.log("Level existences of the first list:");
for (let i = 0; i < levelExistences.length; i++) {
console.log(`- Level ${i + 1} (index ${i}): ${levelExistences[i]}`);
}
});
paragraphs
获取正文中的对象集合 Paragraph 。
readonly paragraphs: Word.ParagraphCollection;
属性值
注解
重要提示:要求集 1.1 和 1.2 不会返回表中的段落。 从要求集 1.3 中,还返回表中的段落。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-word-count.yaml
// Counts how many times each term appears in the document.
await Word.run(async (context) => {
const paragraphs: Word.ParagraphCollection = context.document.body.paragraphs;
paragraphs.load("text");
await context.sync();
// Split up the document text using existing spaces as the delimiter.
let text = [];
paragraphs.items.forEach((item) => {
let paragraph = item.text.trim();
if (paragraph) {
paragraph.split(" ").forEach((term) => {
let currentTerm = term.trim();
if (currentTerm) {
text.push(currentTerm);
}
});
}
});
// Determine the list of unique terms.
let makeTextDistinct = new Set(text);
let distinctText = Array.from(makeTextDistinct);
let allSearchResults = [];
for (let i = 0; i < distinctText.length; i++) {
let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
results.load("text");
// Map each search term with its results.
let correlatedResults = {
searchTerm: distinctText[i],
hits: results
};
allSearchResults.push(correlatedResults);
}
await context.sync();
// Display the count for each search term.
allSearchResults.forEach((result) => {
let length = result.hits.items.length;
console.log(`Search term: ${result.searchTerm} => Count: ${length}`);
});
});
parentBody
获取 body 的父正文。 例如,表格单元格 body 的父正文可能是标题。 如果没有父正文,则引发 ItemNotFound 错误。
readonly parentBody: Word.Body;
属性值
注解
parentBodyOrNullObject
获取 body 的父正文。 例如,表格单元格 body 的父正文可能是标题。 如果没有父正文,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentBodyOrNullObject: Word.Body;
属性值
注解
parentContentControl
获取包含正文的内容控件。 如果没有父内容控件,则引发 ItemNotFound 错误。
readonly parentContentControl: Word.ContentControl;
属性值
注解
parentContentControlOrNullObject
获取包含正文的内容控件。 如果没有父内容控件,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentContentControlOrNullObject: Word.ContentControl;
属性值
注解
parentSection
获取 body 的父节。 如果没有父节,则引发 ItemNotFound 错误。
readonly parentSection: Word.Section;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-section-breaks.yaml
// Gets the section after the current selection when another section is expected.
await Word.run(async (context) => {
const selection: Word.Range = context.document.getSelection();
const selectedBody: Word.Body = selection.parentBody;
const selectedSection: Word.Section = selectedBody.parentSection;
const nextSection: Word.Section = selectedSection.getNext();
const nextSectionBody: Word.Body = nextSection.body;
nextSectionBody.load("text");
await context.sync();
console.log(`Next section text: ${nextSectionBody.text}`);
});
parentSectionOrNullObject
获取 body 的父节。 如果没有父节,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentSectionOrNullObject: Word.Section;
属性值
注解
shapes
获取正文中的对象集合 Shape ,包括内联形状和浮动形状。 目前仅支持以下形状:文本框、几何形状、组、图片和画布。
readonly shapes: Word.ShapeCollection;
属性值
注解
重要提示: 请注意,随着时间的推移,可能会支持其他类型的形状。 因此,加载项应请求和处理特定类型的形状。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-shapes-text-boxes.yaml
await Word.run(async (context) => {
// Gets text boxes in the main document.
const shapes: Word.ShapeCollection = context.document.body.shapes;
shapes.load();
await context.sync();
if (shapes.items.length > 0) {
console.log(`Number of shapes found in the main document: ${shapes.items.length}`);
shapes.items.forEach(function (shape, index) {
if (shape.type === Word.ShapeType.textBox) {
console.log(`Shape ${index} in the main document has a text box. Properties:`, shape);
} else {
console.log(`Shape ${index} in the main document doesn't have a text box.`);
}
});
} else {
console.log("No shapes found in the main document.");
}
});
style
指定正文的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。
style: string;
属性值
string
注解
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"
注解
tables
获取正文中的对象集合 Table 。
readonly tables: Word.TableCollection;
属性值
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml
// Gets the content of the first cell in the first table.
await Word.run(async (context) => {
const firstCell: Word.Body = context.document.body.tables.getFirst().getCell(0, 0).body;
firstCell.load("text");
await context.sync();
console.log("First cell's text is: " + firstCell.text);
});
text
获取正文的文本。 使用 insertText 插入文本的方法。
readonly text: string;
属性值
string
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Gets the text content of the body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to load the text in document body.
body.load("text");
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Body contents (text): " + body.text);
});
type
获取 body 的类型。 类型可以是 mainDoc、section、header、 footer或 。tableCell WordApi 1.5 及更高版本支持其他类型 footnote、 endnote和 noteItem 。
readonly type: Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem" | "Shape";
属性值
Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem" | "Shape"
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Gets the referenced note's item type and body type, which are both "Footnote".
await Word.run(async (context) => {
const footnotes: Word.NoteItemCollection = context.document.body.footnotes;
footnotes.load("items");
await context.sync();
const referenceNumber = (document.getElementById("input-reference") as HTMLInputElement).value;
const mark = Number.parseInt(referenceNumber, 10) - 1;
const item: Word.NoteItem = footnotes.items[mark];
console.log(`Note type of footnote ${referenceNumber}: ${item.type}`);
item.body.load("type");
await context.sync();
console.log(`Body type of note: ${item.body.type}`);
});
方法详细信息
clear()
清除对象的内容 Body 。 用户可以对已清除的内容执行撤消操作。
clear(): void;
返回
void
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Clears out the content from the document body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to clear the contents of the body.
body.clear();
console.log("Cleared the body contents.");
});
// The Silly stories add-in sample shows how the clear method can be used to clear the contents of a document.
// https://aka.ms/sillystorywordaddin
getComments()
获取与正文关联的注释。
getComments(): Word.CommentCollection;
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-comments.yaml
// Gets the comments in the document body.
await Word.run(async (context) => {
const comments: Word.CommentCollection = context.document.body.getComments();
// Load objects to log in the console.
comments.load();
await context.sync();
console.log("All comments:", comments);
});
getContentControls(options)
获取正文中当前支持的内容控件。
getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;
参数
- options
- Word.ContentControlOptions
可选。 用于定义返回哪些内容控件的选项。
返回
注解
重要提示: 如果在 options 参数中提供了特定类型,则仅返回受支持类型的内容控件。 请注意,使用通用 Word 的方法将引发异常。与特定类型无关的 ContentControl。 随着时间的推移,可能会支持其他类型的内容控件。 因此,加载项应请求和处理特定类型的内容控件。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/get-change-tracking-states.yaml
// Deletes the first content control found in the document body.
await Word.run(async (context) => {
context.document.body
.getContentControls()
.getFirst()
.delete(false);
await context.sync();
console.log("Deleted the first content control.");
});
getHtml()
获取对象的 HTML 表示形式 Body 。 在网页或 HTML 查看器中呈现时,格式将与文档的格式非常匹配,但不完全匹配。 此方法不会为不同平台上的同一文档返回完全相同的 HTML, (Windows、Mac、Word Web 等 ) 。 如果需要精确的保真度或跨平台的一致性,请使用 Body.getOoxml() 返回的 XML 并将其转换为 HTML。
getHtml(): OfficeExtension.ClientResult<string>;
返回
OfficeExtension.ClientResult<string>
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Gets the HTML that represents the content of the body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to get the HTML contents of the body.
const bodyHTML = body.getHtml();
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Body contents (HTML): " + bodyHTML.value);
});
getOoxml()
获取对象的 Body OOXML (Office Open XML) 表示形式。
getOoxml(): OfficeExtension.ClientResult<string>;
返回
OfficeExtension.ClientResult<string>
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Gets the OOXML that represents the content of the body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to get the OOXML contents of the body.
const bodyOOXML = body.getOoxml();
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Body contents (OOXML): " + bodyOOXML.value);
});
getRange(rangeLocation)
获取整个正文或正文的起点/终点,作为一个范围。
getRange(rangeLocation?: Word.RangeLocation.whole | Word.RangeLocation.start | Word.RangeLocation.end | Word.RangeLocation.after | Word.RangeLocation.content | "Whole" | "Start" | "End" | "After" | "Content"): Word.Range;
参数
- rangeLocation
-
whole | start | end | after | content | "Whole" | "Start" | "End" | "After" | "Content"
可选。 范围位置必须为 whole、 、 endstartafter、 或 。content
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/20-lists/format-list-range.yaml
// Gets the range covering the entire body and reads list formatting properties.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const listFormat: Word.ListFormat = bodyRange.listFormat;
listFormat.load("isSingleList, listType, listLevelNumber, listString, listValue");
await context.sync();
console.log("List format info for the body range:");
console.log(`- Is single list: ${listFormat.isSingleList}`);
console.log(`- List type: ${listFormat.listType}`);
console.log(`- List level number (first paragraph): ${listFormat.listLevelNumber}`);
console.log(`- List string (first paragraph): "${listFormat.listString}"`);
console.log(`- List value (first paragraph): ${listFormat.listValue}`);
});
getReviewedText(changeTrackingVersion)
根据 ChangeTrackingVersion 选择获取已审阅的文本。
getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;
参数
- changeTrackingVersion
- Word.ChangeTrackingVersion
可选。 值必须为 OR 。originalcurrent 默认值为 current。
返回
OfficeExtension.ClientResult<string>
注解
getReviewedText(changeTrackingVersion)
根据 ChangeTrackingVersion 选择获取已审阅的文本。
getReviewedText(changeTrackingVersion?: "Original" | "Current"): OfficeExtension.ClientResult<string>;
参数
- changeTrackingVersion
-
"Original" | "Current"
可选。 值必须为 OR 。originalcurrent 默认值为 current。
返回
OfficeExtension.ClientResult<string>
注解
getTrackedChanges()
获取正文中对象的 TrackedChange 集合。
getTrackedChanges(): Word.TrackedChangeCollection;
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-tracked-changes.yaml
// Gets the tracked changes and logs their details.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
const trackedChanges: Word.TrackedChangeCollection = body.getTrackedChanges();
trackedChanges.load("items/author, items/date, items/text, items/type");
await context.sync();
if (trackedChanges.items.length === 0) {
console.warn("No tracked changes were found.");
return;
}
trackedChanges.items.forEach((trackedChange: Word.TrackedChange, index: number) => {
console.log(`Tracked change ${index + 1}:`, {
author: trackedChange.author,
date: trackedChange.date,
text: trackedChange.text,
type: trackedChange.type,
});
});
});
insertBreak(breakType, insertLocation)
在主文档的指定位置插入分隔符。
insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): void;
参数
- breakType
-
Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"
要添加到正文的分隔符类型。
返回
void
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts a page break at the beginning of the document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to insert a page break at the start of the document body.
body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Added a page break at the start of the document body.");
});
insertContentControl(contentControlType)
Body使用内容控件包装对象。
insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | Word.ContentControlType.dropDownList | Word.ContentControlType.comboBox | Word.ContentControlType.buildingBlockGallery | Word.ContentControlType.datePicker | Word.ContentControlType.repeatingSection | Word.ContentControlType.picture | Word.ContentControlType.group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"): Word.ContentControl;
参数
- contentControlType
-
richText | plainText | checkBox | dropDownList | comboBox | buildingBlockGallery | datePicker | repeatingSection | picture | group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"
可选。 要插入的内容控件类型。 必须是 richText、 picturecomboBoxbuildingBlockGalleryrepeatingSectiondatePickergroupplainTextcheckBoxdropDownList或 。 默认值为 richText。
返回
注解
注意:该 contentControlType 参数是在 WordApi 1.5 中引入的。
plainText WordApi 1.5 中添加了支持。
checkBox WordApi 1.7 中添加了支持。
dropDownList 并且 comboBox 在 WordApi 1.9 中添加了支持。 WordApiDesktop 1.3 中添加了对 buildingBlockGallery、datePicker、picturegroup、和repeatingSection的支持。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Creates a content control using the document body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to wrap the body in a content control.
body.insertContentControl();
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Wrapped the body in a content control.");
});
insertFileFromBase64(base64File, insertLocation)
将文档插入到正文中的指定位置。 要插入的文档的最大大小为 4 MB。
insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;
参数
- base64File
-
string
.docx 文件的 Base64 编码内容。
返回
注解
如果要插入的文档包含 ActiveX 控件,则不支持插入, (可能在表单字段) 中。 请考虑将此类窗体字段替换为适合你的场景的内容控件或其他选项。
如果要插入的文档包含链接或外部内容,则不支持插入。 如果是这样,此方法将返回错误 InvalidArgument 。
插入文档时不保留文档设置。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts the body from the external document at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to insert the Base64-encoded string representation of the body of the selected .docx file at the beginning of the current document.
body.insertFileFromBase64(externalDocument, Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Added Base64-encoded text to the beginning of the document body.");
});
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。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts the HTML at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to insert HTML at the beginning of the document.
body.insertHtml("<strong>This is text inserted with body.insertHtml()</strong>", Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("HTML added to the beginning of the document body.");
});
insertInlinePictureFromBase64(base64EncodedImage, insertLocation)
将图片插入到正文中的指定位置。
insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.InlinePicture;
参数
- base64EncodedImage
-
string
要插入正文中的 Base64 编码图像。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts an image inline at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Base64-encoded image to insert inline.
const base64EncodedImg =
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";
// Queue a command to insert a Base64-encoded image at the beginning of the current document.
body.insertInlinePictureFromBase64(base64EncodedImg, Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Added a Base64-encoded image to the beginning of the document body.");
});
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。
返回
注解
如果要插入的内容包含链接的内容或外部内容,则不支持插入。 如果是这样,此方法将返回错误 InvalidArgument 。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts OOXML at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to insert OOXML at the beginning of the body.
body.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>",
Word.InsertLocation.start
);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Added OOXML to the beginning of the document body.");
});
// Read "Understand when and how to use Office Open XML in your Word add-in" 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
// The Word-Add-in-DocumentAssembly sample shows how you can use this API to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly
insertParagraph(paragraphText, insertLocation)
在指定位置插入段落。
insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.Paragraph;
参数
- paragraphText
-
string
要插入的段落文本。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-formatted-text.yaml
await Word.run(async (context) => {
// Second sentence, let's insert it as a paragraph after the previously inserted one.
const secondSentence: Word.Paragraph = context.document.body.insertParagraph(
"This is the first text with a custom style.",
"End"
);
secondSentence.font.set({
bold: false,
italic: true,
name: "Berlin Sans FB",
color: "blue",
size: 30
});
await context.sync();
});
insertTable(rowCount, columnCount, insertLocation, values)
插入包含指定行数和列数的 table。
insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End", values?: string[][]): Word.Table;
参数
- rowCount
-
number
表格的行数。
- columnCount
-
number
表格的列数。
- values
-
string[][]
可选的二维数组。 如果指定数组中的对应字符串,则填充单元格。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml
await Word.run(async (context) => {
// Use a two-dimensional array to hold the initial table values.
const data = [
["Tokyo", "Beijing", "Seattle"],
["Apple", "Orange", "Pineapple"]
];
const table: Word.Table = context.document.body.insertTable(2, 3, "Start", data);
table.styleBuiltIn = Word.BuiltInStyleName.gridTable5Dark_Accent2;
table.styleFirstColumn = false;
await context.sync();
});
insertText(text, insertLocation)
将文本插入到正文中的指定位置。
insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;
参数
- text
-
string
要插入的文本。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Inserts text at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to insert text at the beginning of the current document.
body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
await context.sync();
console.log("Text added to the beginning of the document body.");
});
load(options)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(options?: Word.Interfaces.BodyLoadOptions): Word.Body;
参数
- options
- Word.Interfaces.BodyLoadOptions
为要加载的对象属性提供选项。
返回
load(propertyNames)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(propertyNames?: string | string[]): Word.Body;
参数
- propertyNames
-
string | string[]
指定要加载的属性的逗号分隔的字符串或字符串数组。
返回
load(propertyNamesAndPaths)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(propertyNamesAndPaths?: {
select?: string;
expand?: string;
}): Word.Body;
参数
- propertyNamesAndPaths
-
{ select?: string; expand?: string; }
propertyNamesAndPaths.select 是指定要加载的属性的逗号分隔字符串,以及 propertyNamesAndPaths.expand 指定要加载的导航属性的逗号分隔字符串。
返回
search(searchText, searchOptions)
使用指定的搜索选项对对象范围执行 Body 搜索。 搜索结果是对象的 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
搜索文本。 最多可包含 255 个字符。
- searchOptions
-
Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }
可选。 用于搜索的选项。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/search.yaml
// Does a basic text search and highlights matches in the document.
await Word.run(async (context) => {
const results : Word.RangeCollection = context.document.body.search("extend");
results.load("length");
await context.sync();
// Let's traverse the search results and highlight matches.
for (let i = 0; i < results.items.length; i++) {
results.items[i].font.highlightColor = "yellow";
}
await context.sync();
});
...
// Does a wildcard search and highlights matches in the document.
await Word.run(async (context) => {
// Construct a wildcard expression and set matchWildcards to true in order to use wildcards.
const results : Word.RangeCollection = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
results.load("length");
await context.sync();
// Let's traverse the search results and highlight matches.
for (let i = 0; i < results.items.length; i++) {
results.items[i].font.highlightColor = "red";
results.items[i].font.color = "white";
}
await context.sync();
});
select(selectionMode)
选择正文并在 Word UI 中进行浏览。
select(selectionMode?: Word.SelectionMode): void;
参数
- selectionMode
- Word.SelectionMode
可选。 选择模式必须为 select、 、start 或 end。
select 为默认值。
返回
void
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml
// Selects the entire body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy object for the document body.
const body: Word.Body = context.document.body;
// Queue a command to select the document body.
// The Word UI will move to the selected document body.
body.select();
console.log("Selected the document body.");
});
select(selectionMode)
选择正文并在 Word UI 中进行浏览。
select(selectionMode?: "Select" | "Start" | "End"): void;
参数
- selectionMode
-
"Select" | "Start" | "End"
可选。 选择模式必须为 select、 、start 或 end。
select 为默认值。
返回
void
注解
set(properties, options)
同时设置对象的多个属性。 可以传递具有相应属性的纯文本对象,也可以传递另一个相同类型的 API 对象。
set(properties: Interfaces.BodyUpdateData, options?: OfficeExtension.UpdateOptions): void;
参数
- properties
- Word.Interfaces.BodyUpdateData
一个 JavaScript 对象,其属性与调用该方法的对象的属性同构结构。
- options
- OfficeExtension.UpdateOptions
提供一个选项,用于在 properties 对象尝试设置任何只读属性时禁止错误。
返回
void
set(properties)
toJSON()
覆盖 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 (JSON.stringify反过来调用 toJSON 传递给它的对象的方法。) 虽然原始 Word.Body 对象是 API 对象, toJSON 但该方法返回一个纯 JavaScript 对象, (类型化为 Word.Interfaces.BodyData) ,其中包含从原始对象加载的任何子属性的浅层副本。
toJSON(): Word.Interfaces.BodyData;
返回
track()
根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果在调用中 .sync 使用此对象,并且在“.run”批处理的顺序执行之外使用此对象,并且在设置属性或对对象调用方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将对象添加到跟踪对象集合。 如果此对象是集合的一部分,您还应跟踪父集合。
track(): Word.Body;
返回
untrack()
释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 需要在内存释放生效之前调用 context.sync() 。
untrack(): Word.Body;
返回
事件详细信息
onCommentAdded
注意
此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。
在添加新批注时发生。
readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
事件类型
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/comment-events.yaml
// Listen for new comments anywhere in the document body.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
body.track();
// Resolve the tracked body's reference before subscribing.
await context.sync();
const handler: OfficeExtension.EventHandlerResult<Word.CommentEventArgs> =
body.onCommentAdded.add(onEventHandler);
eventRegistrations.push({ body, handler });
await context.sync();
});
onCommentChanged
注意
此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。
更改注释或其回复时发生。
readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
事件类型
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/comment-events.yaml
// Listen for changes to comments and replies in the document body.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
body.track();
// Resolve the tracked body's reference before subscribing.
await context.sync();
const handler: OfficeExtension.EventHandlerResult<Word.CommentEventArgs> =
body.onCommentChanged.add(onChangedHandler);
eventRegistrations.push({ body, handler });
await context.sync();
});
onCommentDeleted
注意
此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。
删除注释时发生。
readonly onCommentDeleted: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
事件类型
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/comment-events.yaml
// Listen for comments deleted from the document body.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
body.track();
// Resolve the tracked body's reference before subscribing.
await context.sync();
const handler: OfficeExtension.EventHandlerResult<Word.CommentEventArgs> =
body.onCommentDeleted.add(onEventHandler);
eventRegistrations.push({ body, handler });
await context.sync();
});
onCommentDeselected
注意
此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。
取消选择批注时出现。
readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
事件类型
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/comment-events.yaml
// Listen for comments losing selection in the document body.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
body.track();
// Resolve the tracked body's reference before subscribing.
await context.sync();
const handler: OfficeExtension.EventHandlerResult<Word.CommentEventArgs> =
body.onCommentDeselected.add(onEventHandler);
eventRegistrations.push({ body, handler });
await context.sync();
});
onCommentSelected
注意
此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。
选中批注时出现。
readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;
事件类型
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/comment-events.yaml
// Listen for comments being selected in the document body.
await Word.run(async (context) => {
const body: Word.Body = context.document.body;
body.track();
// Resolve the tracked body's reference before subscribing.
await context.sync();
const handler: OfficeExtension.EventHandlerResult<Word.CommentEventArgs> =
body.onCommentSelected.add(onEventHandler);
eventRegistrations.push({ body, handler });
await context.sync();
});