Word.Range class
表示文档中的一个连续区域。
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-comments.yaml
// Gets the range of the first comment in the selected content.
await Word.run(async (context) => {
const comment: Word.Comment = context.document.getSelection().getComments().getFirstOrNullObject();
comment.load("contentRange");
const range: Word.Range = comment.getRange();
range.load("text");
await context.sync();
if (comment.isNullObject) {
console.warn("No comments in the selection, so no range to get.");
return;
}
console.log(`Comment location: ${range.text}`);
const contentRange: Word.CommentContentRange = comment.contentRange;
console.log("Comment content range:", contentRange);
});
属性
| content |
获取区域中对象的 |
| context | 与 对象关联的请求上下文。 这会将加载项的进程连接到 Office 主机应用程序的进程。 |
| endnotes | 获取区域中尾注的集合。 |
| fields | 获取区域中对象的 |
| font | 获取区域的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。 |
| footnotes | 获取区域中脚注的集合。 |
| hyperlink | 获取 range 内的第一个超链接,或在 range 内设置超链接。 在 range 内设置新的超链接将删除 range 内的所有超链接。 使用“#”将地址部分与可选位置部件分开。 |
| inline |
获取区域中对象的 |
| is |
检查 range 长度是否为零。 |
| lists | 获取区域中对象的 |
| paragraphs | 获取区域中对象的 |
| parent |
获取 range 的父正文。 |
| parent |
获取当前支持的内容控件,该控件包含 区域。
|
| parent |
获取当前支持的内容控件,该控件包含 区域。 如果没有父内容控件,则此方法将返回其属性设置为 |
| parent |
获取包含 range 的 table。
|
| parent |
获取包含 range 的 tableCell。
|
| parent |
获取包含 range 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 |
| parent |
获取包含 range 的 table。 如果它未包含在表中,则此方法将返回一个 对象,其 |
| style | 指定区域的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。 |
| style |
指定区域的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 若要使用自定义样式或本地化样式名称,请参阅“style”属性。 |
| tables | 获取区域中对象的 |
| text | 获取区域的文本。 |
方法
| clear() | 清除 对象的内容 |
| compare |
比较此范围与另一范围的位置。 |
| delete() | 从文档中删除区域及其内容。 |
| expand |
返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果两个 |
| expand |
返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果这两个区域没有联合,则此方法将返回一个 对象,其 |
| get |
获取区域内或重叠的所有书签的名称。 如果书签名称以下划线字符开头,则隐藏书签。 |
| get |
获取与区域关联的注释。 |
| get |
获取区域中当前支持的内容控件。 |
| get |
获取 对象的 HTML 表示形式 |
| get |
获取相应范围内的超链接子范围。 |
| get |
使用标点符号和其他结束标记获取下一个文本区域。
|
| get |
使用标点符号和其他结束标记获取下一个文本区域。 如果此文本范围是最后一个,则此方法将返回一个对象,其 |
| get |
获取 对象的 OOXML 表示形式 |
| get |
|
| get |
根据 ChangeTrackingVersion 选择获取审阅的文本。 |
| get |
根据 ChangeTrackingVersion 选择获取审阅的文本。 |
| get |
使用标点符号和其他结束标记获取区域中的文本子区域。 |
| get |
获取区域中对象的集合 |
| highlight() | 在不更改文档内容的情况下暂时突出显示区域。 若要永久突出显示文本,请设置区域的 |
| insert |
在区域上插入书签。 如果某个位置存在同名书签,则首先将其删除。 |
| insert |
在主文档的指定位置插入分隔符。 |
| insert |
在区域上插入注释。 |
| insert |
|
| insert |
插入尾注。 尾注引用放置在区域之后。 |
| insert |
在指定位置插入字段。 |
| insert |
在指定位置插入字段。 |
| insert |
在指定位置插入 document。 |
| insert |
插入脚注。 脚注引用放置在区域之后。 |
| insert |
在指定位置插入 HTML。 |
| insert |
在指定位置插入图片。 |
| insert |
在指定位置插入 OOXML。 |
| insert |
在指定位置插入段落。 |
| insert |
插入包含指定行数和列数的 table。 |
| insert |
在指定位置插入文本。 |
| intersect |
返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个 |
| intersect |
返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个区域不重叠或相邻,则此方法将返回一个 对象,其 |
| load(options) | 将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| load(property |
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| load(property |
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 |
| remove |
删除 方法添加 |
| search(search |
对对象范围 |
| select(selection |
选择并在 Word UI 中导航到区域。 |
| select(selection |
选择并在 Word UI 中导航到区域。 |
| set(properties, options) | 同时设置对象的多个属性。 可以传递具有相应属性的纯对象,也可以传递同一类型的另一个 API 对象。 |
| set(properties) | 基于现有的已加载对象,同时对对象设置多个属性。 |
| split(delimiters, multi |
使用分隔符将相应范围拆分为各个子范围。 |
| toJSON() | 重写 JavaScript |
| track() | 根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果跨 |
| untrack() | 释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 在内存发布生效之前,需要调用 |
属性详细信息
contentControls
获取区域中对象的 ContentControl 集合。
readonly contentControls: Word.ContentControlCollection;
属性值
注解
context
endnotes
获取区域中尾注的集合。
readonly endnotes: Word.NoteItemCollection;
属性值
注解
fields
获取区域中对象的 Field 集合。
readonly fields: Word.FieldCollection;
属性值
注解
font
获取区域的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。
readonly font: Word.Font;
属性值
注解
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 selected document range.
await Word.run(async (context) => {
const footnotes: Word.NoteItemCollection = context.document.getSelection().footnotes;
footnotes.load("length");
await context.sync();
console.log("Number of footnotes in the selected range: " + footnotes.items.length);
});
hyperlink
获取 range 内的第一个超链接,或在 range 内设置超链接。 在 range 内设置新的超链接将删除 range 内的所有超链接。 使用“#”将地址部分与可选位置部件分开。
hyperlink: string;
属性值
string
注解
inlinePictures
获取区域中对象的 InlinePicture 集合。
readonly inlinePictures: Word.InlinePictureCollection;
属性值
注解
isEmpty
lists
获取区域中对象的 List 集合。
readonly lists: Word.ListCollection;
属性值
注解
paragraphs
获取区域中对象的 Paragraph 集合。
readonly paragraphs: Word.ParagraphCollection;
属性值
注解
重要提示:对于要求集 1.1 和 1.2,不会返回完全包含在此范围内的表中的段落。 从要求集 1.3 中,还会返回此类表中的段落。
parentBody
parentContentControl
获取当前支持的内容控件,该控件包含 区域。
ItemNotFound如果没有父内容控件,则引发错误。
readonly parentContentControl: 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 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}`
);
});
parentContentControlOrNullObject
获取当前支持的内容控件,该控件包含 区域。 如果没有父内容控件,则此方法将返回其属性设置为 true的对象isNullObject。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentContentControlOrNullObject: Word.ContentControl;
属性值
注解
parentTable
获取包含 range 的 table。
ItemNotFound如果未包含在表中,则引发错误。
readonly parentTable: Word.Table;
属性值
注解
parentTableCell
获取包含 range 的 tableCell。
ItemNotFound如果表单元格中未包含错误,则引发错误。
readonly parentTableCell: Word.TableCell;
属性值
注解
parentTableCellOrNullObject
获取包含 range 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentTableCellOrNullObject: Word.TableCell;
属性值
注解
parentTableOrNullObject
获取包含 range 的 table。 如果它未包含在表中,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性。
readonly parentTableOrNullObject: Word.Table;
属性值
注解
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"
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/doc-assembly.yaml
await Word.run(async (context) => {
const header: Word.Range = context.document.body.insertText("This is a sample Heading 1 Title!!\n",
"Start" /*this means at the beginning of the body */);
header.styleBuiltIn = Word.BuiltInStyleName.heading1;
await context.sync();
});
tables
获取区域中对象的 Table 集合。
readonly tables: Word.TableCollection;
属性值
注解
text
方法详细信息
clear()
清除 对象的内容 Range 。 用户可以对已清除的内容执行撤消操作。
clear(): void;
返回
void
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to clear the contents of the proxy range object.
range.clear();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log('Cleared the selection (range object)');
});
compareLocationWith(range)
比较此范围与另一范围的位置。
compareLocationWith(range: Word.Range): OfficeExtension.ClientResult<Word.LocationRelation>;
参数
- range
- Word.Range
要与此范围进行比较的范围。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml
// Compares the location of one paragraph in relation to another paragraph.
await Word.run(async (context) => {
const paragraphs: Word.ParagraphCollection = context.document.body.paragraphs;
paragraphs.load("items");
await context.sync();
const firstParagraphAsRange: Word.Range = paragraphs.items[0].getRange();
const secondParagraphAsRange: Word.Range = paragraphs.items[1].getRange();
const comparedLocation = firstParagraphAsRange.compareLocationWith(secondParagraphAsRange);
await context.sync();
const locationValue: Word.LocationRelation = comparedLocation.value;
console.log(`Location of the first paragraph in relation to the second paragraph: ${locationValue}`);
});
delete()
从文档中删除区域及其内容。
delete(): void;
返回
void
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to delete the range object.
range.delete();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log('Deleted the selection (range object)');
});
expandTo(range)
返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果两个 ItemNotFound 范围没有联合,则引发错误。
expandTo(range: Word.Range): Word.Range;
参数
- range
- Word.Range
另一个范围。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml
await Word.run(async (context) => {
// Get the complete sentence (as range) associated with the insertion point.
const sentences: Word.RangeCollection = context.document
.getSelection()
.getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
sentences.load("$none");
await context.sync();
// Expand the range to the end of the paragraph to get all the complete sentences.
const sentencesToTheEndOfParagraph: Word.RangeCollection = sentences.items[0]
.getRange()
.expandTo(
context.document
.getSelection()
.paragraphs.getFirst()
.getRange(Word.RangeLocation.end)
)
.getTextRanges(["."], false /* Don't trim spaces*/);
sentencesToTheEndOfParagraph.load("text");
await context.sync();
for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
console.log(sentencesToTheEndOfParagraph.items[i].text);
}
});
expandToOrNullObject(range)
返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果这两个区域没有联合,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性。
expandToOrNullObject(range: Word.Range): Word.Range;
参数
- range
- Word.Range
另一个范围。
返回
注解
getBookmarks(includeHidden, includeAdjacent)
获取区域内或重叠的所有书签的名称。 如果书签名称以下划线字符开头,则隐藏书签。
getBookmarks(includeHidden?: boolean, includeAdjacent?: boolean): OfficeExtension.ClientResult<string[]>;
参数
- includeHidden
-
boolean
可选。 指示是否包含隐藏的书签。
false默认值指示已排除隐藏的书签。
- includeAdjacent
-
boolean
可选。 指示是否包含与区域相邻的书签。
false默认值,指示排除相邻书签。
返回
OfficeExtension.ClientResult<string[]>
注解
getComments()
获取与区域关联的注释。
getComments(): Word.CommentCollection;
返回
一个 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 selected content.
await Word.run(async (context) => {
const comments: Word.CommentCollection = context.document.getSelection().getComments();
// Load objects to log in the console.
comments.load();
await context.sync();
console.log("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/insert-and-change-checkbox-content-control.yaml
// Deletes 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");
await context.sync();
if (selectedContentControl.isNullObject) {
const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
parentContentControl.load("id,type");
await context.sync();
if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
console.warn("No checkbox content control is currently selected.");
return;
} else {
selectedContentControl = parentContentControl;
}
}
console.log(`About to delete checkbox content control with id: ${selectedContentControl.id}`);
selectedContentControl.delete(false);
await context.sync();
console.log("Deleted checkbox content control.");
});
getHtml()
获取 对象的 HTML 表示形式 Range 。 在网页或 HTML 查看器中呈现时,格式将与文档的格式相匹配,但不完全匹配。 此方法不会为不同平台上的相同文档返回完全相同的 HTML, (Windows、Mac、web 上的Word等 ) 。 如果需要精确保真度或跨平台的一致性,请使用 Range.getOoxml() 返回的 XML 并将其转换为 HTML。
getHtml(): OfficeExtension.ClientResult<string>;
返回
OfficeExtension.ClientResult<string>
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to get the HTML of the current selection.
const html = range.getHtml();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log('The HTML read from the document was: ' + html.value);
});
getHyperlinkRanges()
获取相应范围内的超链接子范围。
getHyperlinkRanges(): Word.RangeCollection;
返回
注解
示例
await Word.run(async (context) => {
// Get the entire document body.
const bodyRange = context.document.body.getRange(Word.RangeLocation.whole);
// Get all the ranges that only consist of hyperlinks.
const hyperLinks = bodyRange.getHyperlinkRanges();
hyperLinks.load("hyperlink");
await context.sync();
// Log each hyperlink.
hyperLinks.items.forEach((linkRange) => {
console.log(linkRange.hyperlink);
});
});
getNextTextRange(endingMarks, trimSpacing)
使用标点符号和其他结束标记获取下一个文本区域。
ItemNotFound如果此文本范围是最后一个文本范围,则引发错误。
getNextTextRange(endingMarks: string[], trimSpacing?: boolean): Word.Range;
参数
- endingMarks
-
string[]
标点符号和其他结束标记作为字符串数组。
- trimSpacing
-
boolean
可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 返回的范围的开头和末尾的间距字符。 默认值, false 指示包含范围开头和末尾的间距字符。
返回
注解
getNextTextRangeOrNullObject(endingMarks, trimSpacing)
使用标点符号和其他结束标记获取下一个文本区域。 如果此文本范围是最后一个,则此方法将返回一个对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性。
getNextTextRangeOrNullObject(endingMarks: string[], trimSpacing?: boolean): Word.Range;
参数
- endingMarks
-
string[]
标点符号和其他结束标记作为字符串数组。
- trimSpacing
-
boolean
可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 返回的范围的开头和末尾的间距字符。 默认值, false 指示包含范围开头和末尾的间距字符。
返回
注解
getOoxml()
获取 对象的 OOXML 表示形式 Range 。
getOoxml(): OfficeExtension.ClientResult<string>;
返回
OfficeExtension.ClientResult<string>
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to get the OOXML of the current selection.
const ooxml = range.getOoxml();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log('The OOXML read from the document was: ' + ooxml.value);
});
getRange(rangeLocation)
Range克隆对象,或获取该区域的起始点或终点作为新区域。
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、、endstart、 after或 。content
返回
注解
示例
// 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
// Places a dropdown list content control at the end of the selection.
await Word.run(async (context) => {
let selection = context.document.getSelection();
selection.getRange(Word.RangeLocation.end).insertContentControl(Word.ContentControlType.dropDownList);
await context.sync();
console.log("Dropdown list content control inserted at the end of the selection.");
});
getReviewedText(changeTrackingVersion)
根据 ChangeTrackingVersion 选择获取审阅的文本。
getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;
参数
- changeTrackingVersion
- Word.ChangeTrackingVersion
可选。 该值必须是 original 或 current。 默认值为 current。
返回
OfficeExtension.ClientResult<string>
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-change-tracking.yaml
// Gets the reviewed text.
await Word.run(async (context) => {
const range: Word.Range = context.document.getSelection();
const before = range.getReviewedText(Word.ChangeTrackingVersion.original);
const after = range.getReviewedText(Word.ChangeTrackingVersion.current);
await context.sync();
console.log("Reviewed text (before):", before.value, "Reviewed text (after):", after.value);
});
getReviewedText(changeTrackingVersion)
根据 ChangeTrackingVersion 选择获取审阅的文本。
getReviewedText(changeTrackingVersion?: "Original" | "Current"): OfficeExtension.ClientResult<string>;
参数
- changeTrackingVersion
-
"Original" | "Current"
可选。 该值必须是 original 或 current。 默认值为 current。
返回
OfficeExtension.ClientResult<string>
注解
getTextRanges(endingMarks, trimSpacing)
使用标点符号和其他结束标记获取区域中的文本子区域。
getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;
参数
- endingMarks
-
string[]
标点符号和其他结束标记作为字符串数组。
- trimSpacing
-
boolean
可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 范围集合中返回的范围的开头和末尾的间距字符。
false默认值,指示范围集合中包含范围开头和末尾的间距字符。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml
await Word.run(async (context) => {
// Get the complete sentence (as range) associated with the insertion point.
const sentences: Word.RangeCollection = context.document
.getSelection()
.getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
sentences.load("$none");
await context.sync();
// Expand the range to the end of the paragraph to get all the complete sentences.
const sentencesToTheEndOfParagraph: Word.RangeCollection = sentences.items[0]
.getRange()
.expandTo(
context.document
.getSelection()
.paragraphs.getFirst()
.getRange(Word.RangeLocation.end)
)
.getTextRanges(["."], false /* Don't trim spaces*/);
sentencesToTheEndOfParagraph.load("text");
await context.sync();
for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
console.log(sentencesToTheEndOfParagraph.items[i].text);
}
});
getTrackedChanges()
获取区域中对象的集合 TrackedChange 。
getTrackedChanges(): Word.TrackedChangeCollection;
返回
注解
highlight()
在不更改文档内容的情况下暂时突出显示区域。 若要永久突出显示文本,请设置区域的 font.highlightColor。
highlight(): void;
返回
void
注解
insertBookmark(name)
在区域上插入书签。 如果某个位置存在同名书签,则首先将其删除。
insertBookmark(name: string): void;
参数
- name
-
string
不区分大小写的书签名称。 仅支持字母数字和下划线字符。 它必须以字母开头,但如果要将书签标记为隐藏,则以下划线字符开头。 名称不能超过 40 个字符。
返回
void
注解
注意:插入书签的条件类似于在Word UI 中插入书签。 若要详细了解如何在Word UI 中管理书签,请参阅添加或删除Word文档或 Outlook 邮件中的书签。
insertBreak(breakType, insertLocation)
在主文档的指定位置插入分隔符。
insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): void;
参数
- breakType
-
Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"
要添加的中断类型。
返回
void
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert a page break after the selected text.
range.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 selected text.');
});
insertComment(commentText)
在区域上插入注释。
insertComment(commentText: string): Word.Comment;
参数
- commentText
-
string
要插入的注释文本。
返回
Comment插入的对象。
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-comments.yaml
// Sets a comment on the selected content.
await Word.run(async (context) => {
const text = (document.getElementById("comment-text") as HTMLInputElement).value;
const comment: Word.Comment = context.document.getSelection().insertComment(text);
// Load object to log in the console.
comment.load();
await context.sync();
console.log("Comment inserted:", comment);
});
insertContentControl(contentControlType)
Range使用内容控件包装 对象。
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、、plainText、checkBox、dropDownListcomboBox、buildingBlockGallerydatePicker、repeatingSection、、 picture或 。group 默认值为 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/90-scenarios/doc-assembly.yaml
// Simulates creation of a template. First searches the document for instances of the string "Contractor",
// then changes the format of each search result,
// then wraps each search result within a content control,
// finally sets a tag and title property on each content control.
await Word.run(async (context) => {
const results: Word.RangeCollection = context.document.body.search("Contractor");
results.load("font/bold");
// Check to make sure these content controls haven't been added yet.
const customerContentControls: Word.ContentControlCollection = context.document.contentControls.getByTag("customer");
customerContentControls.load("text");
await context.sync();
if (customerContentControls.items.length === 0) {
for (let i = 0; i < results.items.length; i++) {
results.items[i].font.bold = true;
let cc: Word.ContentControl = results.items[i].insertContentControl();
cc.tag = "customer"; // This value is used in the next step of this sample.
cc.title = "Customer Name " + i;
}
}
await context.sync();
});
insertEndnote(insertText)
插入尾注。 尾注引用放置在区域之后。
insertEndnote(insertText?: string): Word.NoteItem;
参数
- insertText
-
string
可选。 要插入尾注正文的文本。 默认值为“”。
返回
注解
insertField(insertLocation, fieldType, text, removeFormatting)
在指定位置插入字段。
insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: Word.FieldType, text?: string, removeFormatting?: boolean): Word.Field;
参数
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
相对于将插入字段的区域的位置。 该值必须为 replace、、start、endbefore、 或 。after
- fieldType
- Word.FieldType
可选。 可以是任何 FieldType 值。 默认值 empty为 。
- text
-
string
可选。 指定字段类型的其他属性或选项(如果需要)。
- removeFormatting
-
boolean
可选。
true 若要删除在更新期间应用于字段的格式, false 则为 ,否则为 。 默认值 false为 。
返回
注解
重要提示:在 Windows 和 Mac 上的 Word 中,API 支持插入和管理Word中列出的所有类型。FieldType 除外Word.FieldType.others。 在 web 上的Word中,字段主要是只读的。 若要了解详细信息,请参阅在Word外接程序中使用字段。
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-fields.yaml
// Inserts a Date field before selection.
await Word.run(async (context) => {
const range: Word.Range = context.document.getSelection().getRange();
const field: Word.Field = range.insertField(Word.InsertLocation.before, Word.FieldType.date, '\\@ "M/d/yyyy h:mm am/pm"', true);
field.load("result,code");
await context.sync();
if (field.isNullObject) {
console.log("There are no fields in this document.");
} else {
console.log("Code of the field: " + field.code, "Result of the field: " + JSON.stringify(field.result));
}
});
insertField(insertLocation, fieldType, text, removeFormatting)
在指定位置插入字段。
insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: "Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined", text?: string, removeFormatting?: boolean): Word.Field;
参数
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
相对于将插入字段的区域的位置。 该值必须为 replace、、start、endbefore、 或 。after
- fieldType
-
"Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined"
可选。 可以是任何 FieldType 值。 默认值 empty为 。
- text
-
string
可选。 指定字段类型的其他属性或选项(如果需要)。
- removeFormatting
-
boolean
可选。
true 若要删除在更新期间应用于字段的格式, false 则为 ,否则为 。 默认值 false为 。
返回
注解
重要提示:在 Windows 和 Mac 上的 Word 中,API 支持插入和管理Word中列出的所有类型。FieldType 除外Word.FieldType.others。 在 web 上的Word中,字段主要是只读的。 若要了解详细信息,请参阅在Word外接程序中使用字段。
insertFileFromBase64(base64File, insertLocation)
在指定位置插入 document。
insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;
参数
- base64File
-
string
.docx 文件的 Base64 编码内容。
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
该值必须为 replace、、start、endbefore、 或 。after
返回
注解
如果要插入的文档在窗体字段中) 中包含 ActiveX 控件 (,则不支持插入。 请考虑将此类窗体字段替换为适合你的方案的内容控件或其他选项。
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert base64 encoded .docx at the beginning of the range.
// You'll need to implement getBase64() to make this work.
range.insertFileFromBase64(getBase64(), 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 range.');
});
insertFootnote(insertText)
插入脚注。 脚注引用放置在区域之后。
insertFootnote(insertText?: string): Word.NoteItem;
参数
- insertText
-
string
可选。 要插入到脚注正文中的文本。 默认值为“”。
返回
注解
示例
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Sets a footnote on the selected content.
await Word.run(async (context) => {
const text = (document.getElementById("input-footnote") as HTMLInputElement).value;
const footnote: Word.NoteItem = context.document.getSelection().insertFootnote(text);
await context.sync();
console.log("Inserted footnote.");
});
insertHtml(html, insertLocation)
在指定位置插入 HTML。
insertHtml(html: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;
参数
- html
-
string
要插入的 HTML。
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
该值必须为 replace、、start、endbefore、 或 。after
返回
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert HTML in to the beginning of the range.
range.insertHtml('<strong>This is text inserted with range.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 range.');
});
insertInlinePictureFromBase64(base64EncodedImage, insertLocation)
在指定位置插入图片。
insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.InlinePicture;
参数
- base64EncodedImage
-
string
要插入的 Base64 编码图像。
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
该值必须为 replace、、start、endbefore、 或 。after
返回
注解
示例
// 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) => {
// Inserts a picture at the start of the first text box.
const firstShapeWithTextBox: Word.Shape = context.document.body.shapes
.getByTypes([Word.ShapeType.textBox])
.getFirst();
firstShapeWithTextBox.load("type/body");
await context.sync();
const startRange: Word.Range = firstShapeWithTextBox.body.getRange(Word.RangeLocation.start);
const newPic: Word.InlinePicture = startRange.insertInlinePictureFromBase64(
getPictureBase64(),
Word.InsertLocation.start
);
newPic.load();
await context.sync();
console.log("New inline picture properties:", newPic);
});
...
// Returns Base64-encoded image data for a sample picture.
const pictureBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABblBMVEX+7tEYMFlyg5v8zHXVgof///+hrL77qRnIWmBEWXq6MDgAF0/i1b//8dP+79QKJ1MAIFL8yWpugZz/+O/VzLwzTXR+jaP/z3PHzdjNaWvuxrLFT1n8znmMj5fFTFP25OHlsa2wqqJGW3z7pgCbqsH936oAJlWnssRzdoLTd1HTfINbY3a7tar90IxJVG0AH1ecmJH//90gN14AFU/nxInHVFL80YQAD03qv3LUrm7cwJLWjoLenpPRdXTQgoj15sz+57/7szr93KPbiWjUvZj95LnwzLmMX3L8wmz7rib8xnP8vVz91JT8ukvTz8i8vsORkJKvsLIAD1YwPViWnKZVYHbKuqHjwo3ur2/Pa2O+OTvHVETfj1tybm9qdYlsYlnkmmC0DSPirpvAq4bj5uuono7tu5vgpannnX3ksbSKg5bv0tTclJNFSlyZgpPqwsW4go2giWdbWV+3mmuWgpRcbolURmReS2embHkiRHBcZ6c8AAALcElEQVR4nO3di1cTVx4H8AyThmC484ghFzSxEDRhIRBIMEFQA1qoVhAqYBVd3UXcri1dd7fLdv3vdybJZF73zr2TufPyzPccew49hc6H331nZkylkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiQJ6wj2hH1JLKNo9p/sPB3X8rRUau/f2f56kML2k/n5+XFDSjzPQ7l95+swCqkfzDy1hnwvsLT9FRCF1I7Fpwt5Xt6PfRmF1LgNaBAqZdyNOVGwV9AkVMq4HOshR3iCAJqFalONr1HYRQGtQsXYvrONmjKj7xae0QnVuaO0/OiOlv3lfqI/1G4jgShhnzkIfzA/SNgAUoR9d0I9g/9wfjtsAiHocWZ8fIckLA1ad/SFB0jg+AGxhgN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Ab/ar5aa7By0QV+HuTBVMXtl8GGGzezraxXXMQ3+96bGOru6bAnNf7D608EUBgNXWKGW0nJ8BsOCtY4or1Ise5f+FKCBa2HtqBUwujWK0LqbBXMfThqVFO56CbgUNtAulwa0uYK2wkHM9WtiOecHkqRcj7UEAqH+ZwkVq5fS0ctzRcPxSNhtzC5yUc5NO03pFABQWRFc/w5jWC7oSpgr4TJoDLB0JdCfdBfH7VSbh0UPbSqnj5XvxK2aXP4P485IkSZIkSZIkSZIkSZIkSZIkSZIk8Tv/B3bBREdOWYS3AAAAAElFTkSuQmCC";
return pictureBase64;
insertOoxml(ooxml, insertLocation)
在指定位置插入 OOXML。
insertOoxml(ooxml: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;
参数
- ooxml
-
string
要插入的 OOXML。
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
该值必须为 replace、、start、endbefore、 或 。after
返回
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert OOXML in to the beginning of the range.
range.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('OOXML added to the beginning of the range.');
});
// Read "Create better add-ins for Word with Office Open XML" for guidance on working with OOXML.
// https://free.blessedness.top/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml
insertParagraph(paragraphText, insertLocation)
在指定位置插入段落。
insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): Word.Paragraph;
参数
- paragraphText
-
string
要插入的段落文本。
返回
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert the paragraph after the range.
range.insertParagraph('Content of a new paragraph', 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('Paragraph added to the end of the range.');
});
insertTable(rowCount, columnCount, insertLocation, values)
插入包含指定行数和列数的 table。
insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After", values?: string[][]): Word.Table;
参数
- rowCount
-
number
表格的行数。
- columnCount
-
number
表格的列数。
- values
-
string[][]
可选的二维数组。 如果指定数组中的对应字符串,则填充单元格。
返回
注解
insertText(text, insertLocation)
在指定位置插入文本。
insertText(text: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;
参数
- text
-
string
要插入的文本。
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
该值必须为 replace、、start、endbefore、 或 。after
返回
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert the paragraph at the end of the range.
range.insertText('New text inserted into the range.', 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('Text added to the end of the range.');
});
intersectWith(range)
返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个 ItemNotFound 区域不重叠或相邻,则引发错误。
intersectWith(range: Word.Range): Word.Range;
参数
- range
- Word.Range
另一个范围。
返回
注解
intersectWithOrNullObject(range)
返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个区域不重叠或相邻,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性。
intersectWithOrNullObject(range: Word.Range): Word.Range;
参数
- range
- Word.Range
另一个范围。
返回
注解
load(options)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(options?: Word.Interfaces.RangeLoadOptions): Word.Range;
参数
- options
- Word.Interfaces.RangeLoadOptions
提供要加载对象的属性的选项。
返回
load(propertyNames)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(propertyNames?: string | string[]): Word.Range;
参数
- propertyNames
-
string | string[]
逗号分隔的字符串或指定要加载的属性的字符串数组。
返回
load(propertyNamesAndPaths)
将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()。
load(propertyNamesAndPaths?: {
select?: string;
expand?: string;
}): Word.Range;
参数
- propertyNamesAndPaths
-
{ select?: string; expand?: string; }
propertyNamesAndPaths.select 是一个逗号分隔的字符串,指定要加载的属性,是 propertyNamesAndPaths.expand 一个逗号分隔的字符串,指定要加载的导航属性。
返回
removeHighlight()
search(searchText, searchOptions)
对对象范围 Range 使用指定的搜索选项执行搜索。 搜索结果是对象的集合 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; }
可选。 用于搜索的选项。
返回
注解
select(selectionMode)
选择并在 Word UI 中导航到区域。
select(selectionMode?: Word.SelectionMode): void;
参数
- selectionMode
- Word.SelectionMode
可选。 选择模式必须是 select、 start或 end。
select 为默认值。
返回
void
注解
示例
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
const range = context.document.getSelection();
// Queue a command to insert HTML in to the beginning of the range.
range.insertHtml('<strong>This is text inserted with range.insertHtml()</strong>', Word.InsertLocation.start);
// Queue a command to select the HTML that was inserted.
range.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 range.');
});
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.RangeUpdateData, options?: OfficeExtension.UpdateOptions): void;
参数
- properties
- Word.Interfaces.RangeUpdateData
一个 JavaScript 对象,其属性按同构方式构造为调用方法的对象的属性。
- options
- OfficeExtension.UpdateOptions
提供一个选项,用于在 properties 对象尝试设置任何只读属性时禁止显示错误。
返回
void
set(properties)
split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)
使用分隔符将相应范围拆分为各个子范围。
split(delimiters: string[], multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;
参数
- delimiters
-
string[]
分隔符作为字符串数组。
- multiParagraphs
-
boolean
可选。 指示返回的子区域是否可以涵盖多个段落。 默认值指示 false 段落边界也用作分隔符。
- trimDelimiters
-
boolean
可选。 指示是否从范围集合中的区域剪裁分隔符。
false默认值,指示分隔符包含在范围集合中返回的区域中。
- trimSpacing
-
boolean
可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 范围集合中返回的范围的开头和末尾的间距字符。
false默认值,指示范围集合中包含范围开头和末尾的间距字符。
返回
注解
toJSON()
重写 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。
JSON.stringify
(,依次调用toJSON传递给它的 对象的 方法。) 虽然原始Word.Range对象是 API 对象,toJSON但该方法返回一个纯 JavaScript 对象, (类型为 Word.Interfaces.RangeData) ,其中包含从原始对象加载的任何子属性的浅表副本。
toJSON(): Word.Interfaces.RangeData;
返回
track()
根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果跨 .sync 调用和“.run”批处理的顺序执行外部使用此对象,并在设置属性或调用对象方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将该对象添加到跟踪的对象集合。 如果此对象是集合的一部分,则还应跟踪父集合。
track(): Word.Range;
返回
untrack()
释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 在内存发布生效之前,需要调用 context.sync() 。
untrack(): Word.Range;