Word.Range class

表示文档中的一个连续区域。

扩展

注解

API 集:WordApi 1.1

使用方

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Reads the text and checks whether the first paragraph range is empty.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.load("text,isEmpty,style");
    await context.sync();
    console.log("First paragraph's properties:", { text: paragraphRange.text, isEmpty: paragraphRange.isEmpty, style: paragraphRange.style });
});

属性

bold

指定区域是否格式化为粗体。

boldBidirectional

指定在从右到左的语言文档中,范围是否格式化为粗体。

bookmarks

返回表示 BookmarkCollection 区域内所有书签的对象。

borders

返回 BorderUniversalCollection 表示该区域的所有边框的对象。

case

指定一个 CharacterCase 值,该值表示区域内文本的大小写。

characterWidth

指定范围的字符宽度。

combineCharacters

指定范围是否包含组合字符。

conflicts

返回ConflictCollection包含所有 Word 的对象。冲突范围内的对象。

contentControls

获取范围内对象的 ContentControl 集合。

context

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

disableCharacterSpaceGrid

指定 Microsoft Word 是否忽略相应Range对象的每行字符数。

editors

返回一个 EditorCollection 对象,该对象表示当文档处于受保护 (只读) 模式时有权修改范围的所有用户。

emphasisMark

指定字符或指定字符串的强调符号。

end

指定范围的结束字符位置。

endnotes

获取范围中的尾注集合。

fields

获取范围内对象的 Field 集合。

fitTextWidth

指定当前度量单位) 的宽度 (Microsoft Word适合当前所选内容或区域中的文本。

font

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

footnotes

获取范围内脚注的集合。

frames

获取 FrameCollection 表示范围内所有帧的对象。

grammarChecked

指定是否已对区域或文档运行语法检查。

hasNoProofing

指定范围) 拼写和语法检查 (校对状态。

highlightColorIndex

指定范围的突出显示颜色。

horizontalInVertical

指定竖排文本中设置的横排文本的格式。

hyperlink

获取 range 内的第一个超链接,或在 range 内设置超链接。 在 range 内设置新的超链接将删除 range 内的所有超链接。 使用“#”将地址部分与可选位置部分分隔。

hyperlinks

返回 HyperlinkCollection 表示区域内所有超链接的对象。

id

指定范围的 ID。

inlinePictures

获取范围内对象的 InlinePicture 集合。

isEmpty

检查 range 长度是否为零。

isEndOfRowMark

获取范围是否折叠且位于表中的行尾标记处。

isTextVisibleOnScreen

获取范围内的文本在屏幕上是否可见。

italic

指定字体或区域是否格式化为斜体。

italicBidirectional

指定字体或区域的格式是否为斜体 (从右到左的语言) 。

kana

指定日语文本的范围是平假名还是片假名。

languageDetected

指定 Microsoft Word 是否检测到区域中文本的语言。

languageId

指定表示 LanguageId 范围语言的值。

languageIdFarEast

指定范围的东亚语言。

languageIdOther

为未归类为东亚语言的范围指定一种语言。

listFormat

返回表示 ListFormat 区域的所有列表格式特征的对象。

lists

获取范围内对象的 List 集合。

pages

获取范围内的页集合。

paragraphs

获取范围内对象的 Paragraph 集合。

parentBody

获取 range 的父正文。

parentContentControl

获取包含范围的当前支持的内容控件。 如果没有父内容控件,则引发 ItemNotFound 错误。

parentContentControlOrNullObject

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

parentTable

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

parentTableCell

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

parentTableCellOrNullObject

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

parentTableOrNullObject

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

revisions

获取表示范围中跟踪更改的修订集合。

sections

获取范围内部分的集合。

shading

返回一个 ShadingUniversal 对象,它引用范围的底纹格式。

shapes

获取定位在范围内的对象集合 Shape ,包括内联和浮动形状。 目前仅支持以下形状:文本框、几何形状、组、图片和画布。

showAll

指定是否显示所有非打印字符 (,如隐藏文本、制表符、空格标记和段落标记) 。

spellingChecked

指定是否已在整个区域或文档中检查拼写。

start

指定区域的起始字符位置。

storyLength

获取文章中包含范围的字符数。

storyType

获取范围的故事类型。

style

指定范围的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。

styleBuiltIn

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

tableColumns

获取 TableColumnCollection 表示区域内所有表列的对象。

tables

获取范围内对象的 Table 集合。

text

获取区域的文本。

twoLinesInOne

指定 Microsoft Word 是否将两行文本合二为一,并指定包围文本的字符(如果有)。

underline

指定应用于范围的下划线类型。

方法

clear()

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

compareLocationWith(range)

比较此范围与另一范围的位置。

delete()

从文档中删除区域及其内容。

detectLanguage()

分析区域文本以确定它所写入的语言。

expandTo(range)

返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果两个范围没有联合,则引发 ItemNotFound 错误。

expandToOrNullObject(range)

返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果这两个范围没有联合,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

getBookmarks(includeHidden, includeAdjacent)

获取名称:范围内或重叠的所有书签。 如果书签名称以下划线字符开头,则该书签将被隐藏。

getComments()

获取与范围关联的注释。

getContentControls(options)

获取范围内当前支持的内容控件。

getHtml()

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

getHyperlinkRanges()

获取相应范围内的超链接子范围。

getNextTextRange(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取下一个文本区域。 如果此文本区域是最后一个文本区域,则引发 ItemNotFound 错误。

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取下一个文本区域。 如果此文本区域是最后一个,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

getOoxml()

获取对象的 Range OOXML 表示形式。

getRange(rangeLocation)

克隆 Range 对象,或者将范围的起点或终点作为新范围获取。

getReviewedText(changeTrackingVersion)

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

getReviewedText(changeTrackingVersion)

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

getTextRanges(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取文本区域中的子区域。

getTrackedChanges()

获取范围内对象的 TrackedChange 集合。

highlight()

在不更改文档内容的情况下暂时突出显示范围。 若要永久突出显示文本,请设置范围的 font.highlightColor。

insertBookmark(name)

在范围上插入书签。 如果某处存在同名书签,则会首先将其删除。

insertBreak(breakType, insertLocation)

在主文档的指定位置插入分隔符。

insertCanvas(insertShapeOptions)

在文本前面插入浮动画布,其定位点位于区域的开头。

insertComment(commentText)

插入有关范围的注释。

insertContentControl(contentControlType)

Range使用内容控件包装对象。

insertEndnote(insertText)

插入尾注。 尾注引用放在范围之后。

insertField(insertLocation, fieldType, text, removeFormatting)

在指定位置插入字段。

insertField(insertLocation, fieldType, text, removeFormatting)

在指定位置插入字段。

insertFileFromBase64(base64File, insertLocation)

在指定位置插入 document。 要插入的文档的最大大小为 4 MB。

insertFootnote(insertText)

插入脚注。 脚注引用放置在区域之后。

insertGeometricShape(geometricShapeType, insertShapeOptions)

在文本前面插入几何形状,定位点位于区域的开头。

insertGeometricShape(geometricShapeType, insertShapeOptions)

在文本前面插入几何形状,定位点位于区域的开头。

insertHtml(html, insertLocation)

在指定位置插入 HTML。

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

在指定位置插入图片。

insertOoxml(ooxml, insertLocation)

在指定位置插入 OOXML。

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertPictureFromBase64(base64EncodedImage, insertShapeOptions)

在文本前面插入浮动图片,其定位点位于区域的开头。

insertTable(rowCount, columnCount, insertLocation, values)

插入包含指定行数和列数的 table。

insertText(text, insertLocation)

在指定位置插入文本。

insertTextBox(text, insertShapeOptions)

在文本前面插入浮动文本框,其定位点位于区域的开头。

intersectWith(range)

返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个范围不重叠或不相邻,则引发 ItemNotFound 错误。

intersectWithOrNullObject(range)

返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果这两个区域不重叠或不相邻,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

removeHighlight()

删除由该 highlight 方法添加的突出显示(如果有)。

search(searchText, searchOptions)

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

select(selectionMode)

选择并在 Word UI 中导航到区域。

select(selectionMode)

选择并在 Word UI 中导航到区域。

set(properties, options)

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

set(properties)

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

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将相应范围拆分为各个子范围。

toJSON()

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

track()

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

untrack()

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

事件

onCommentAdded

在添加新批注时发生。

onCommentChanged

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

onCommentDeselected

取消选择批注时出现。

onCommentSelected

选中批注时出现。

属性详细信息

bold

指定区域是否格式化为粗体。

readonly bold: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml

// Reads character formatting on the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("text,bold,italic,boldBidirectional,italicBidirectional,case,highlightColorIndex");
    await context.sync();
    console.log("First paragraph's formatting:", {
        text: paragraphRange.text,
        bold: paragraphRange.bold,
        italic: paragraphRange.italic,
        boldBidirectional: paragraphRange.boldBidirectional,
        italicBidirectional: paragraphRange.italicBidirectional,
        case: paragraphRange.case,
        highlightColorIndex: paragraphRange.highlightColorIndex
    });
});

boldBidirectional

指定在从右到左的语言文档中,范围是否格式化为粗体。

readonly boldBidirectional: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

bookmarks

返回表示 BookmarkCollection 区域内所有书签的对象。

readonly bookmarks: Word.BookmarkCollection;

属性值

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Read bookmark properties and the text enclosed by each bookmark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const bookmarks: Word.BookmarkCollection = paragraphRange.bookmarks;
    bookmarks.load("items/name,items/start,items/end,items/isEmpty,items/isColumn,items/storyType,items/range/text");
    await context.sync();
    console.log(`Bookmarks found: ${bookmarks.items.length}`);
    bookmarks.items.forEach((bookmark: Word.Bookmark) => {
        console.log("Bookmark details:", {
            name: bookmark.name,
            start: bookmark.start,
            end: bookmark.end,
            isEmpty: bookmark.isEmpty,
            isColumn: bookmark.isColumn,
            storyType: bookmark.storyType,
            text: bookmark.range.text
        });
    });
});

borders

返回 BorderUniversalCollection 表示该区域的所有边框的对象。

readonly borders: Word.BorderUniversalCollection;

属性值

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/range-borders-and-shading-desktop.yaml

// Reads the border formatting of the first paragraph's text.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const borders: Word.BorderUniversalCollection = paragraphRange.borders;
    borders.load("items/color,items/lineStyle,items/lineWidth,items/isVisible");
    await context.sync();
    console.log("First paragraph's border formatting:");
    borders.items.forEach((border: Word.BorderUniversal) => {
        console.log("Border:", {
            color: border.color,
            lineStyle: border.lineStyle,
            lineWidth: border.lineWidth,
            isVisible: border.isVisible
        });
    });
});

case

指定一个 CharacterCase 值,该值表示区域内文本的大小写。

case: Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana";

属性值

Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana"

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml

// Converts the first paragraph's text to uppercase.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const characterCase: Word.CharacterCase = Word.CharacterCase.upper;
    paragraphRange.case = characterCase;
    await context.sync();
    console.log("Converted the first paragraph's text to uppercase.");
});

characterWidth

指定范围的字符宽度。

characterWidth: Word.CharacterWidth | "Half" | "Full";

属性值

Word.CharacterWidth | "Half" | "Full"

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Converts the first paragraph's Latin characters and digits to full width.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const characterWidth: Word.CharacterWidth = Word.CharacterWidth.full;
    paragraphRange.characterWidth = characterWidth;
    await context.sync();
    console.log("Converted the first paragraph's Latin characters and digits to full width.");
});

combineCharacters

指定范围是否包含组合字符。

combineCharacters: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Combines the first paragraph's short group of characters.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.combineCharacters = true;
    await context.sync();
    console.log("Enabled combined characters on the first paragraph. Get layout settings to inspect the flag.");
});

conflicts

返回ConflictCollection包含所有 Word 的对象。冲突范围内的对象。

readonly conflicts: Word.ConflictCollection;

属性值

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/manage-coauthoring-conflicts.yaml

// Gets coauthoring conflicts associated with the selected range.
await Word.run(async (context) => {
    const selectedRange: Word.Range = context.document.getSelection();
    const conflicts: Word.ConflictCollection = selectedRange.conflicts;
    conflicts.load("items/type");
    await context.sync();
    console.log(`Conflicts in the selection: ${conflicts.items.length}`);
    conflicts.items.forEach((conflict: Word.Conflict) => console.log(`Conflict type: ${conflict.type}`));
});

contentControls

获取范围内对象的 ContentControl 集合。

readonly contentControls: Word.ContentControlCollection;

属性值

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Gets the content controls contained in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const contentControls: Word.ContentControlCollection = bodyRange.contentControls;
    contentControls.load("items/tag,items/title,items/text");
    await context.sync();
    console.log(`Content controls found: ${contentControls.items.length}`);
    contentControls.items.forEach((control: Word.ContentControl) => {
        console.log({ tag: control.tag, title: control.title, text: control.text });
    });
});

context

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

context: RequestContext;

属性值

disableCharacterSpaceGrid

指定 Microsoft Word 是否忽略相应Range对象的每行字符数。

readonly disableCharacterSpaceGrid: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

editors

返回一个 EditorCollection 对象,该对象表示当文档处于受保护 (只读) 模式时有权修改范围的所有用户。

readonly editors: Word.EditorCollection;

属性值

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-editing-permissions-desktop.yaml

// Reads editing-permission entries for the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const editors: Word.EditorCollection = paragraphRange.editors;
    const editorCount: OfficeExtension.ClientResult<number> = editors.getCount();
    await context.sync();
    const editorEntries: Word.Editor[] = [];
    for (let index = 0; index < editorCount.value; index++) {
        const editor: Word.Editor = editors.getItemAt(index);
        editor.load("name,id");
        editorEntries.push(editor);
    }
    await context.sync();
    console.log(`Editing-permission entries: ${editorCount.value}`);
    editorEntries.forEach((editor: Word.Editor) => console.log({ name: editor.name, id: editor.id }));
});

emphasisMark

指定字符或指定字符串的强调符号。

readonly emphasisMark: Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle";

属性值

Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle"

注解

API 集:WordApiDesktop 1.4

end

指定范围的结束字符位置。

end: number;

属性值

number

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Selects the first paragraph's text except its last character.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("start,end");
    await context.sync();
    if (paragraphRange.start === paragraphRange.end) {
        console.warn("The paragraph is empty. Run Set up again.");
        return;
    }
    paragraphRange.end = paragraphRange.end - 1;
    paragraphRange.select();
    await context.sync();
    console.log("Selected the range with its ending position reduced by one character.");
});

endnotes

获取范围中的尾注集合。

readonly endnotes: Word.NoteItemCollection;

属性值

注解

API 集:WordApi 1.5

示例

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

// Gets the text of every endnote in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const endnotes: Word.NoteItemCollection = bodyRange.endnotes;
    endnotes.load("items/body/text");
    await context.sync();
    console.log(`Endnotes found: ${endnotes.items.length}`);
    endnotes.items.forEach((endnote: Word.NoteItem) => console.log(endnote.body.text));
});

fields

获取范围内对象的 Field 集合。

readonly fields: Word.FieldCollection;

属性值

注解

API 集:WordApi 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Gets field codes and displayed results in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const fields: Word.FieldCollection = bodyRange.fields;
    fields.load("items/code,items/result/text");
    await context.sync();
    console.log(`Fields found: ${fields.items.length}`);
    fields.items.forEach((field: Word.Field) => console.log({ code: field.code, text: field.result.text }));
});

fitTextWidth

指定当前度量单位) 的宽度 (Microsoft Word适合当前所选内容或区域中的文本。

fitTextWidth: number;

属性值

number

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Fits the first paragraph's text into a specified width.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.fitTextWidth = 100;
    await context.sync();
    console.log("Fitted the first paragraph's text into 100 current measurement units.");
});

font

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

readonly font: Word.Font;

属性值

注解

API 集:WordApi 1.1

示例

// 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) => {
  // Insert the sentence, then adjust the formatting.
  // Note that replace affects the calling object, in this case the entire document body.
  // A similar method can also be used at the range level.
  const sentence: Word.Range = context.document.body.insertText(
    "This is some formatted text!",
    "Replace"
  );
  sentence.font.set({
    name: "Courier New",
    bold: true,
    size: 18
  });

  await context.sync();
});

footnotes

获取范围内脚注的集合。

readonly footnotes: Word.NoteItemCollection;

属性值

注解

API 集:WordApi 1.5

示例

// 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}`);
});

frames

获取 FrameCollection 表示范围内所有帧的对象。

readonly frames: Word.FrameCollection;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads the text and dimensions of frames in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const frames: Word.FrameCollection = bodyRange.frames;
    frames.load("items/width,items/height,items/range/text");
    await context.sync();
    console.log(`Frames found: ${frames.items.length}`);
    frames.items.forEach((frame: Word.Frame) => {
        console.log({ width: frame.width, height: frame.height, text: frame.range.text });
    });
});

grammarChecked

指定是否已对区域或文档运行语法检查。

grammarChecked: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph as needing another grammar check.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.grammarChecked = false;
    await context.sync();
    console.log("Reset the English paragraph's grammar-checked flag. Get language and proofing settings to inspect it.");
});

hasNoProofing

指定范围) 拼写和语法检查 (校对状态。

hasNoProofing: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Disables spelling and grammar checking for the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.hasNoProofing = true;
    await context.sync();
    console.log("Disabled spelling and grammar checking for the English paragraph. Get language and proofing settings to verify it.");
});

highlightColorIndex

指定范围的突出显示颜色。

readonly highlightColorIndex: Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor";

属性值

Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor"

注解

API 集:WordApiDesktop 1.4

horizontalInVertical

指定竖排文本中设置的横排文本的格式。

horizontalInVertical: Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine";

属性值

Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine"

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Keeps the first paragraph's characters horizontal within vertical text.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const horizontalLayout: Word.HorizontalInVerticalType = Word.HorizontalInVerticalType.fitInLine;
    paragraphRange.horizontalInVertical = horizontalLayout;
    await context.sync();
    console.log("Enabled horizontal-in-vertical layout on the first paragraph. Get layout settings to verify it.");
});

获取 range 内的第一个超链接,或在 range 内设置超链接。 在 range 内设置新的超链接将删除 range 内的所有超链接。 使用“#”将地址部分与可选位置部分分隔。

hyperlink: string;

属性值

string

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Links the first paragraph's text to the Word add-in documentation.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.hyperlink = "https://learn.microsoft.com/office/dev/add-ins/word/";
    await context.sync();
    console.log("Linked the summary text to the Word add-in documentation.");
});

返回 HyperlinkCollection 表示区域内所有超链接的对象。

readonly hyperlinks: Word.HyperlinkCollection;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads hyperlink objects and their destinations in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const hyperlinks: Word.HyperlinkCollection = bodyRange.hyperlinks;
    hyperlinks.load("items/address,items/range/text");
    await context.sync();
    console.log(`Hyperlinks found: ${hyperlinks.items.length}`);
    hyperlinks.items.forEach((hyperlink: Word.Hyperlink) => {
        console.log({ address: hyperlink.address, text: hyperlink.range.text });
    });
});

id

指定范围的 ID。

id: string;

属性值

string

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Reads the range's character positions and the story containing it.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("id,start,end,storyLength,storyType,isEndOfRowMark,isTextVisibleOnScreen");
    await context.sync();
    console.log("First paragraph's position and story:", {
        id: paragraphRange.id,
        start: paragraphRange.start,
        end: paragraphRange.end,
        storyLength: paragraphRange.storyLength,
        storyType: paragraphRange.storyType,
        isEndOfRowMark: paragraphRange.isEndOfRowMark,
        isTextVisibleOnScreen: paragraphRange.isTextVisibleOnScreen
    });
});

inlinePictures

获取范围内对象的 InlinePicture 集合。

readonly inlinePictures: Word.InlinePictureCollection;

属性值

注解

API 集:WordApi 1.2

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the dimensions of inline pictures in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const pictures: Word.InlinePictureCollection = bodyRange.inlinePictures;
    pictures.load("items/width,items/height");
    await context.sync();
    console.log(`Inline pictures found: ${pictures.items.length}`);
    pictures.items.forEach((picture: Word.InlinePicture) => console.log({ width: picture.width, height: picture.height }));
});

isEmpty

检查 range 长度是否为零。

readonly isEmpty: boolean;

属性值

boolean

注解

API 集:WordApi 1.3

isEndOfRowMark

获取范围是否折叠且位于表中的行尾标记处。

readonly isEndOfRowMark: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

isTextVisibleOnScreen

获取范围内的文本在屏幕上是否可见。

readonly isTextVisibleOnScreen: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

italic

指定字体或区域是否格式化为斜体。

readonly italic: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

italicBidirectional

指定字体或区域的格式是否为斜体 (从右到左的语言) 。

readonly italicBidirectional: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

kana

指定日语文本的范围是平假名还是片假名。

kana: Word.Kana | "Katakana" | "Hiragana";

属性值

Word.Kana | "Katakana" | "Hiragana"

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/convert-japanese-kana-desktop.yaml

// Converts the sample paragraph's Japanese katakana text to hiragana.
await Word.run(async (context) => {
    const japaneseRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const kana: Word.Kana = Word.Kana.hiragana;
    japaneseRange.kana = kana;
    await context.sync();
    console.log("Converted the Japanese paragraph's text to hiragana.");
});

languageDetected

指定 Microsoft Word 是否检测到区域中文本的语言。

languageDetected: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph's language as not yet detected.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.languageDetected = false;
    await context.sync();
    console.log("Reset the English paragraph's language-detected flag. Get language and proofing settings to inspect it.");
});

languageId

指定表示 LanguageId 范围语言的值。

languageId: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

属性值

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the first paragraph's proofing language to US English.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.englishUS;
    paragraphRange.languageId = language;
    await context.sync();
    console.log("Set the English paragraph's proofing language to US English.");
});

languageIdFarEast

指定范围的东亚语言。

languageIdFarEast: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

属性值

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the Japanese paragraph's East Asian language.
await Word.run(async (context) => {
    const japaneseRange: Word.Range = context.document.body.paragraphs.getLast().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.japanese;
    japaneseRange.languageIdFarEast = language;
    await context.sync();
    console.log("Set the Japanese paragraph's East Asian language to Japanese.");
});

languageIdOther

为未归类为东亚语言的范围指定一种语言。

languageIdOther: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

属性值

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the first paragraph's non-East-Asian language to US English.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.englishUS;
    paragraphRange.languageIdOther = language;
    await context.sync();
    console.log("Set the English paragraph's non-East-Asian language to US English.");
});

listFormat

返回表示 ListFormat 区域的所有列表格式特征的对象。

readonly listFormat: Word.ListFormat;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// 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}`);
});

lists

获取范围内对象的 List 集合。

readonly lists: Word.ListCollection;

属性值

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the identifiers of lists in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const lists: Word.ListCollection = bodyRange.lists;
    lists.load("items/id");
    await context.sync();
    console.log(`Lists found: ${lists.items.length}`);
    lists.items.forEach((list: Word.List) => console.log(`List ID: ${list.id}`));
});

pages

获取范围内的页集合。

readonly pages: Word.PageCollection;

属性值

注解

API 集:WordApiDesktop 1.2

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/36-pages/get-pages.yaml

// Reads the index and text of each page intersecting the selection.
await Word.run(async (context) => {
  const selectedRange: Word.Range = context.document.getSelection();
  const pages: Word.PageCollection = selectedRange.pages;
  pages.load("items/index");
  await context.sync();

  console.log(`Pages in the selection: ${pages.items.length}`);
  const pageRanges: Word.Range[] = [];
  pages.items.forEach((page: Word.Page) => {
    const pageRange: Word.Range = page.getRange(Word.RangeLocation.whole);
    pageRange.load("text");
    pageRanges.push(pageRange);
  });

  await context.sync();

  for (let i = 0; i < pages.items.length; i++) {
    console.log(`Page ${pages.items[i].index} text: ${pageRanges[i].text}`);
  }
});

paragraphs

获取范围内对象的 Paragraph 集合。

readonly paragraphs: Word.ParagraphCollection;

属性值

注解

API 集:WordApi 1.1

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

示例

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

// Accepts the first annotation found in the selected paragraph.
await Word.run(async (context) => {
  const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
  const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
  annotations.load("id,state,critiqueAnnotation");

  await context.sync();

  for (let i = 0; i < annotations.items.length; i++) {
    const annotation: Word.Annotation = annotations.items[i];

    if (annotation.state === Word.AnnotationState.created) {
      console.log(`Accepting ID ${annotation.id}...`);
      annotation.critiqueAnnotation.accept();

      await context.sync();
      break;
    }
  }
});

parentBody

获取 range 的父正文。

readonly parentBody: Word.Body;

属性值

注解

API 集:WordApi 1.3

示例

// 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}`);
});

parentContentControl

获取包含范围的当前支持的内容控件。 如果没有父内容控件,则引发 ItemNotFound 错误。

readonly parentContentControl: Word.ContentControl;

属性值

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-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

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

readonly parentContentControlOrNullObject: Word.ContentControl;

属性值

注解

API 集:WordApi 1.3

示例

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

// Deletes the first date picker content control found in the selection.
await Word.run(async (context) => {
  // First, look if the selection contains a date picker content control.
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.datePicker]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id");

  await context.sync();

  // The selection doesn't contain a date picker, but the cursor might be inside one.
  // Check if the selection's parent content control is a date picker.
  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControlOrNullObject;
    parentContentControl.load("id,type");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.datePicker) {
      console.warn("Please select a date picker content control before selecting Delete.");
      return;
    }
    
    selectedContentControl = parentContentControl;
  }

  console.log(`About to delete date picker content control with ID: ${selectedContentControl.id}`);
  selectedContentControl.delete(false);
  await context.sync();

  console.log("Deleted date picker content control.");
});

parentTable

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

readonly parentTable: Word.Table;

属性值

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the table containing the first table cell's range.
await Word.run(async (context) => {
    const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
    const parentTable: Word.Table = cellRange.parentTable;
    parentTable.load("rowCount,values");
    await context.sync();
    console.log("Parent table:", { rowCount: parentTable.rowCount, values: parentTable.values });
});

parentTableCell

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

readonly parentTableCell: Word.TableCell;

属性值

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the cell containing the first table cell's range.
await Word.run(async (context) => {
    const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
    const parentCell: Word.TableCell = cellRange.parentTableCell;
    parentCell.load("rowIndex,cellIndex,value");
    await context.sync();
    console.log("Parent cell:", { rowIndex: parentCell.rowIndex, cellIndex: parentCell.cellIndex, value: parentCell.value });
});

parentTableCellOrNullObject

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

readonly parentTableCellOrNullObject: Word.TableCell;

属性值

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Checks whether the first paragraph is inside a table cell.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const parentCell: Word.TableCell = paragraphRange.parentTableCellOrNullObject;
    parentCell.load("value");
    await context.sync();
    if (parentCell.isNullObject) {
        console.warn("The first paragraph is not inside a table cell.");
        return;
    }
    console.log(`Parent cell text: ${parentCell.value}`);
});

parentTableOrNullObject

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

readonly parentTableOrNullObject: Word.Table;

属性值

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Checks whether the first paragraph is inside a table.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const parentTable: Word.Table = paragraphRange.parentTableOrNullObject;
    parentTable.load("rowCount");
    await context.sync();
    if (parentTable.isNullObject) {
        console.warn("The first paragraph is not inside a table.");
        return;
    }
    console.log(`Parent table rows: ${parentTable.rowCount}`);
});

revisions

获取表示范围中跟踪更改的修订集合。

readonly revisions: Word.RevisionCollection;

属性值

注解

API 集:WordApiDesktop 1.4

示例

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

// Reads revision metadata for the first paragraph on desktop Word.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const revisions: Word.RevisionCollection = paragraphRange.revisions;
    revisions.load("items/author,items/date,items/type,items/index,items/formatDescription");
    await context.sync();
    console.log(`Revisions in the first paragraph: ${revisions.items.length}`);
    revisions.items.forEach((revision: Word.Revision) => {
        console.log("Revision properties:", {
            author: revision.author,
            date: revision.date,
            type: revision.type,
            index: revision.index,
            formatDescription: revision.formatDescription,
        });
    });
});

sections

获取范围内部分的集合。

readonly sections: Word.SectionCollection;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads the text of sections intersecting the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const sections: Word.SectionCollection = bodyRange.sections;
    sections.load("items/body/text");
    await context.sync();
    console.log(`Sections found: ${sections.items.length}`);
    sections.items.forEach((section: Word.Section) => console.log(section.body.text));
});

shading

返回一个 ShadingUniversal 对象,它引用范围的底纹格式。

readonly shading: Word.ShadingUniversal;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/range-borders-and-shading-desktop.yaml

// Adds a pale blue background to the first paragraph's text.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const shading: Word.ShadingUniversal = paragraphRange.shading;
    shading.backgroundPatternColor = "#DDEBF7";
    await context.sync();
    console.log("Applied pale blue shading.");
});

shapes

获取定位在范围内的对象集合 Shape ,包括内联和浮动形状。 目前仅支持以下形状:文本框、几何形状、组、图片和画布。

readonly shapes: Word.ShapeCollection;

属性值

注解

API 集:WordApiDesktop 1.2

重要提示: 请注意,随着时间的推移,可能会支持其他类型的形状。 因此,加载项应请求和处理特定类型的形状。

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-inspect-floating-pictures-desktop.yaml

// Reads shapes anchored within the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const shapes: Word.ShapeCollection = paragraphRange.shapes;
    shapes.load("items/name,items/type,items/width,items/height");
    await context.sync();
    console.log(`Shapes anchored in the first paragraph: ${shapes.items.length}`);
    shapes.items.forEach((shape: Word.Shape) => {
        console.log("Anchored shape:", { name: shape.name, type: shape.type, width: shape.width, height: shape.height });
    });
});

showAll

指定是否显示所有非打印字符 (,如隐藏文本、制表符、空格标记和段落标记) 。

showAll: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

spellingChecked

指定是否已在整个区域或文档中检查拼写。

spellingChecked: boolean;

属性值

boolean

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph as needing another spelling check.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.spellingChecked = false;
    await context.sync();
    console.log("Reset the English paragraph's spelling-checked flag. Get language and proofing settings to inspect it.");
});

start

指定区域的起始字符位置。

start: number;

属性值

number

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Selects the first paragraph's text except its first character.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("start,end");
    await context.sync();
    if (paragraphRange.start === paragraphRange.end) {
        console.warn("The paragraph is empty. Run Set up again.");
        return;
    }
    paragraphRange.start = paragraphRange.start + 1;
    paragraphRange.select();
    await context.sync();
    console.log("Selected the range with its starting position advanced by one character.");
});

storyLength

获取文章中包含范围的字符数。

readonly storyLength: number;

属性值

number

注解

API 集:WordApiDesktop 1.4

storyType

获取范围的故事类型。

readonly storyType: Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice";

属性值

Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice"

注解

API 集:WordApiDesktop 1.4

style

指定范围的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。

style: string;

属性值

string

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Applies the sample's custom paragraph style to the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.style = "RangeSampleStyle";
    await context.sync();
    console.log("Applied the sample's custom style.");
});

styleBuiltIn

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

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

属性值

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

注解

API 集:WordApi 1.3

示例

// 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();
});

tableColumns

获取 TableColumnCollection 表示区域内所有表列的对象。

readonly tableColumns: Word.TableColumnCollection;

属性值

注解

API 集:WordApiDesktop 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/manage-table-rows-columns-cells.yaml

// Gets properties of the first column in the sample table.
await Word.run(async (context) => {
  const firstTable: Word.Table = context.document.body.tables.getFirst();
  const tableRange: Word.Range = firstTable.getRange();
  const tableColumns: Word.TableColumnCollection = tableRange.tableColumns;
  tableColumns.load("items/columnIndex,items/isFirst,items/isLast,items/width");
  await context.sync();

  const firstColumn: Word.TableColumn = tableColumns.items[0];
  console.log(
    "First table column:",
    `- Index: ${firstColumn.columnIndex}`,
    `- Is first: ${firstColumn.isFirst}`,
    `- Is last: ${firstColumn.isLast}`,
    `- Width: ${firstColumn.width} points`
  );
});

tables

获取范围内对象的 Table 集合。

readonly tables: Word.TableCollection;

属性值

注解

API 集:WordApi 1.3

text

获取区域的文本。

readonly text: string;

属性值

string

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/get-coauthoring-updates.yaml

// Gets the ranges affected by the most recent coauthoring updates merged into the document.
await Word.run(async (context) => {
  const updates: Word.CoauthoringUpdateCollection = context.document.coauthoring.updates;
  updates.load("items/range");
  await context.sync();

  if (updates.items.length === 0) {
    console.log("No recent coauthoring updates found.");
    return;
  }

  console.log(`Found ${updates.items.length} recent update(s).`);

  const ranges = updates.items.map((u) => u.range);
  ranges.forEach((r) => r.load("text"));
  await context.sync();

  ranges.forEach((range, i) => {
    console.log(`  Update ${i + 1}: "${range.text}"`);
  });
});

twoLinesInOne

指定 Microsoft Word 是否将两行文本合二为一,并指定包围文本的字符(如果有)。

twoLinesInOne: Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets";

属性值

Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets"

注解

API 集:WordApiDesktop 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Displays the first paragraph's text as two lines enclosed in parentheses.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const twoLineLayout: Word.TwoLinesInOneType = Word.TwoLinesInOneType.parentheses;
    paragraphRange.twoLinesInOne = twoLineLayout;
    await context.sync();
    console.log("Applied two-line text with parentheses to the first paragraph.");
});

underline

注意

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

指定应用于范围的下划线类型。

readonly underline: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble";

属性值

Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"

注解

API 集:WordApi BETA (仅预览版)

示例

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

// Reads the underline applied to the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("underline");
    await context.sync();
    const singleUnderline: Word.UnderlineType = Word.UnderlineType.single;
    console.log(`Underline type: ${paragraphRange.underline}`);
    console.log(`Has a single underline: ${paragraphRange.underline === singleUnderline}`);
});

方法详细信息

clear()

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

clear(): void;

返回

void

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Removes the first paragraph's text while preserving the paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.clear();
    await context.sync();
    console.log("Cleared the summary text. The paragraph remains.");
});

compareLocationWith(range)

比较此范围与另一范围的位置。

compareLocationWith(range: Word.Range): OfficeExtension.ClientResult<Word.LocationRelation>;

参数

range
Word.Range

要与此范围进行比较的范围。

返回

注解

API 集:WordApi 1.3

示例

// 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: OfficeExtension.ClientResult<Word.LocationRelation> =
    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

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Deletes the first paragraph range, including its paragraph mark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.delete();
    await context.sync();
    console.log("Deleted the first paragraph range.");
});

detectLanguage()

分析区域文本以确定它所写入的语言。

detectLanguage(): OfficeExtension.ClientResult<boolean>;

返回

注解

API 集:WordApiDesktop 1.3

expandTo(range)

返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果两个范围没有联合,则引发 ItemNotFound 错误。

expandTo(range: Word.Range): Word.Range;

参数

range
Word.Range

另一个范围。

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Gets the text spanning the first two paragraphs.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const secondRange: Word.Range = context.document.body.paragraphs.getFirst().getNext().getRange();
    const expandedRange: Word.Range = firstRange.expandTo(secondRange);
    expandedRange.load("text");
    await context.sync();
    console.log(`Expanded text: ${expandedRange.text}`);
});

expandToOrNullObject(range)

返回从此 range 进行任一方向扩展的新 range,以便覆盖另一 range。 此范围不会更改。 如果这两个范围没有联合,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

expandToOrNullObject(range: Word.Range): Word.Range;

参数

range
Word.Range

另一个范围。

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Expands to the selection when both ranges belong to the same story.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const selection: Word.Range = context.document.getSelection();
    const expandedRange: Word.Range = firstRange.expandToOrNullObject(selection);
    expandedRange.load("text");
    await context.sync();
    if (expandedRange.isNullObject) {
        console.warn("The ranges cannot be combined. Select text in the main document body.");
        return;
    }
    console.log(`Expanded text: ${expandedRange.text}`);
});

getBookmarks(includeHidden, includeAdjacent)

获取名称:范围内或重叠的所有书签。 如果书签名称以下划线字符开头,则该书签将被隐藏。

getBookmarks(includeHidden?: boolean, includeAdjacent?: boolean): OfficeExtension.ClientResult<string[]>;

参数

includeHidden

boolean

可选。 指示是否包含隐藏的书签。 默认值为 false 指示排除隐藏的书签。

includeAdjacent

boolean

可选。 指示是否包含与区域相邻的书签。 默认值为 false 指示排除相邻书签。

返回

注解

API 集:WordApi 1.4

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Gets the names of bookmarks within or overlapping the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const bookmarkNames: OfficeExtension.ClientResult<string[]> = paragraphRange.getBookmarks(false, true);
    await context.sync();
    console.log("Bookmark names:", bookmarkNames.value);
});

getComments()

获取与范围关联的注释。

getComments(): Word.CommentCollection;

返回

包含与 CommentCollection 区域关联的所有注释的对象。

注解

API 集:WordApi 1.4

示例

// 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

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

返回

注解

API 集:WordApi 1.5

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

示例

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

// 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、Word Web 等 ) 。 如果需要精确的保真度或跨平台的一致性,请使用 Range.getOoxml() 返回的 XML 并将其转换为 HTML。

getHtml(): OfficeExtension.ClientResult<string>;

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Reads an HTML representation of the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const html: OfficeExtension.ClientResult<string> = paragraphRange.getHtml();
    await context.sync();
    console.log(`Range HTML: ${html.value}`);
});

getHyperlinkRanges()

获取相应范围内的超链接子范围。

getHyperlinkRanges(): Word.RangeCollection;

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the text and destinations of hyperlinks in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const hyperlinkRanges: Word.RangeCollection = bodyRange.getHyperlinkRanges();
    hyperlinkRanges.load("items/text,items/hyperlink");
    await context.sync();
    console.log(`Hyperlinks found: ${hyperlinkRanges.items.length}`);
    hyperlinkRanges.items.forEach((hyperlinkRange: Word.Range) => {
        console.log({ text: hyperlinkRange.text, hyperlink: hyperlinkRange.hyperlink });
    });
});

getNextTextRange(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取下一个文本区域。 如果此文本区域是最后一个文本区域,则引发 ItemNotFound 错误。

getNextTextRange(endingMarks: string[], trimSpacing?: boolean): Word.Range;

参数

endingMarks

string[]

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

trimSpacing

boolean

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

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Gets the sentence following the first sentence in the document.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const firstSentence: Word.Range = paragraphRange.getTextRanges(["?", "."], true).getFirst();
    const nextSentence: Word.Range = firstSentence.getNextTextRange(["?", "."], true);
    nextSentence.load("text");
    await context.sync();
    console.log(`Next sentence: ${nextSentence.text}`);
});

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取下一个文本区域。 如果此文本区域是最后一个,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

getNextTextRangeOrNullObject(endingMarks: string[], trimSpacing?: boolean): Word.Range;

参数

endingMarks

string[]

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

trimSpacing

boolean

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

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Checks for a sentence after the end of the document without throwing.
await Word.run(async (context) => {
    const endRange: Word.Range = context.document.body.getRange(Word.RangeLocation.end);
    const nextSentence: Word.Range = endRange.getNextTextRangeOrNullObject([".", "?"], true);
    nextSentence.load("text");
    await context.sync();
    if (nextSentence.isNullObject) {
        console.warn("There is no sentence after the end of the document.");
        return;
    }
    console.log(`Next sentence: ${nextSentence.text}`);
});

getOoxml()

获取对象的 Range OOXML 表示形式。

getOoxml(): OfficeExtension.ClientResult<string>;

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Reads the OOXML representation of the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const ooxml: OfficeExtension.ClientResult<string> = paragraphRange.getOoxml();
    await context.sync();
    console.log(`Range OOXML: ${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、 、 endstartafter、 或 。content

返回

注解

API 集:WordApi 1.3

示例

// 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

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

返回

注解

API 集:WordApi 1.4

示例

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

// Gets the 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"

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

返回

注解

API 集:WordApi 1.4

getTextRanges(endingMarks, trimSpacing)

使用标点符号和其他结束标记获取文本区域中的子区域。

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

参数

endingMarks

string[]

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

trimSpacing

boolean

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

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml

// Gets complete sentences from the insertion point to the end of its paragraph.
await Word.run(async (context) => {
  const selection: Word.Range = context.document.getSelection();
  const sentences: Word.RangeCollection = selection.getTextRanges(["."], false);
  sentences.load("$none");
  await context.sync();

  const firstSentence: Word.Range = sentences.items[0];
  const paragraphEnd: Word.Range = selection.paragraphs.getFirst().getRange(Word.RangeLocation.end);
  const remainingRange: Word.Range = firstSentence.expandTo(paragraphEnd);
  const sentencesToTheEndOfParagraph: Word.RangeCollection = remainingRange.getTextRanges(["."], false);
  sentencesToTheEndOfParagraph.load("text");
  await context.sync();

  console.log("Sentences from the current sentence to the paragraph end:");
  for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
    console.log(sentencesToTheEndOfParagraph.items[i].text);
  }
});

getTrackedChanges()

获取范围内对象的 TrackedChange 集合。

getTrackedChanges(): Word.TrackedChangeCollection;

返回

注解

API 集:WordApi 1.6

示例

// 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 inside the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const trackedChanges: Word.TrackedChangeCollection = paragraphRange.getTrackedChanges();
    trackedChanges.load("items/author,items/text,items/type");
    await context.sync();
    console.log(`Tracked changes in the first paragraph: ${trackedChanges.items.length}`);
    trackedChanges.items.forEach((change: Word.TrackedChange) => {
        console.log({ author: change.author, text: change.text, type: change.type });
    });
});

highlight()

在不更改文档内容的情况下暂时突出显示范围。 若要永久突出显示文本,请设置范围的 font.highlightColor。

highlight(): void;

返回

void

注解

API 集:WordApi 1.8

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Temporarily highlights the final paragraph without changing its formatting.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    lastRange.highlight();
    await context.sync();
    console.log("Temporarily highlighted the final paragraph.");
});

insertBookmark(name)

在范围上插入书签。 如果某处存在同名书签,则会首先将其删除。

insertBookmark(name: string): void;

参数

name

string

不区分大小写的书签名称。 仅支持字母数字和下划线字符。 它必须以字母开头,但如果要将书签标记为隐藏,请以下划线字符开头名称。 名称不能超过 40 个字符。

返回

void

注解

API 集:WordApi 1.4

注意:插入书签的条件与在 Word UI 中执行此操作的条件类似。 若要了解有关在 Word UI 中管理书签的详细信息,请参阅在 Word 文档或 Outlook 邮件中添加或删除书签。

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Names the first paragraph range, replacing any existing bookmark with this name.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.insertBookmark("RangeSampleSummary");
    await context.sync();
    console.log("Inserted the RangeSampleSummary bookmark. Get bookmark names to verify it.");
});

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"

要添加的中断类型。

insertLocation

before | after | "Before" | "After"

值必须为 OR 。beforeafter

返回

void

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Inserts a page break after the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.insertBreak(Word.BreakType.page, Word.InsertLocation.after);
    await context.sync();
    console.log("Inserted a page break after the summary.");
});

insertCanvas(insertShapeOptions)

在文本前面插入浮动画布,其定位点位于区域的开头。

insertCanvas(insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

参数

insertShapeOptions
Word.InsertShapeOptions

可选。 画布的位置和大小。 默认位置和大小为 (0、0、300、200) 。

返回

注解

API 集:WordApiDesktop 1.2

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-canvases.yaml

await Word.run(async (context) => {
  // Inserts a canvas in the document.
  const canvasShape: Word.Shape = context.document.getSelection().insertCanvas();
  canvasShape.load();
  await context.sync();

  canvasShape.select();
  console.log("Inserted canvas:", canvasShape);

  const canvas: Word.Canvas = canvasShape.canvas;
  canvas.load("shape,shapes");
  await context.sync();

  console.log("Canvas object:", canvas);
});

insertComment(commentText)

插入有关范围的注释。

insertComment(commentText: string): Word.Comment;

参数

commentText

string

要插入的注释文本。

返回

Comment插入的对象。

注解

API 集:WordApi 1.4

示例

// 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、 picturecomboBoxbuildingBlockGalleryrepeatingSectiondatePickergroupplainTextcheckBoxdropDownList或 。 默认值为 richText。

返回

注解

API 集:WordApi 1.1

注意:该 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

可选。 要插入尾注正文的文本。 默认值为 “”。

返回

注解

API 集:WordApi 1.5

示例

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

// Adds an endnote to the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const endnote: Word.NoteItem = paragraphRange.insertEndnote("Source: the sample document.");
    await context.sync();
    console.log("Inserted an endnote. Its text appears at the end of the document.");
});

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、beforeendstart或 。after

fieldType
Word.FieldType

可选。 可以是任何 FieldType 值。 默认值为 empty。

text

string

可选。 如果指定的字段类型需要其他属性或选项。

removeFormatting

boolean

可选。 true 删除在更新期间应用于字段的格式, false 否则。 默认值为 false。

返回

注解

API 集:WordApi 1.5

重要提示:在 Windows 版和 Mac 版 Word 中,API 支持插入和管理 Word 中列出的所有类型。FieldType except Word.FieldType.others. 在 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、beforeendstart或 。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。

返回

注解

API 集:WordApi 1.5

重要提示:在 Windows 版和 Mac 版 Word 中,API 支持插入和管理 Word 中列出的所有类型。FieldType except Word.FieldType.others. 在 Word 网页版中,字段主要是只读的。 若要了解详细信息,请参阅在 Word 加载项中使用字段。

insertFileFromBase64(base64File, insertLocation)

在指定位置插入 document。 要插入的文档的最大大小为 4 MB。

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、beforeendstart或 。after

返回

注解

API 集:WordApi 1.1

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

如果要插入的文档包含链接或外部内容,则不支持插入。 如果是这样,此方法将返回错误 InvalidArgument 。

插入文档时不保留文档设置。

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph with the contents of a small embedded DOCX file.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    // The DOCX contains one paragraph: "Imported project update."
    const base64File: string = "UEsDBBQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH2QuQ7CMAyGX6XKiqgRAwOiLMAKDLyAlbptRC7FLsfbk3INCBjt//gsLw7XSFxcnPVcqU4kzgFYd+SQyxDJZ6UJyaHkMbUQUR+xJZhOJjPQwQt5GcvQoZaLNTXYWyk2l7xmE3ylEllWxephHFiVwhit0ShZh5OvPyjjJ6HMybuHOxN5lA0KvhIG5TfgmdudKCVTU7HHJFt02QXnkGqog+5dTpb/a77cGZrGaHrnh7aYgiZm41tny7fi0PjX/XB/9/IGUEsDBBQAAAAIAAAAIVBhey9DiQAAAPIAAAALAAAAX3JlbHMvLnJlbHONzzsOAiEQBuCrEA6ws1pYGKCy2dZ4AQLDIy6PDBj19lJYrMbCcuaffH9GnHHVPZbcQqyNPdKam+Sh93oEaCZg0m0qFfNIXKGk+xjJQ9Xmqj3Cfp4PQFuDK7E12WIlp8XuOLs8K/5jF+eiwVMxt4S5/6j4uhiyJo9d8nshC/a9ngbLQQn4eFG9AFBLAwQUAAAACAAAACFQZhg8uIUAAAC1AAAAEQAAAHdvcmQvZG9jdW1lbnQueG1sRY47DsIwDIavUvUAdcXAEIXubFwhJKYtquPIcZVye5IysHyW/T9kW0xgvxNG7Q7aYjbl1i+qyQBkvyC5PHDCWLUXCzmtq8xQWEIS9pjzGmfa4DKOVyC3xn6yxTw5fNpMDdKg050Si2Loau6NXrs9Bac4WGhqo5w8M7kaHgLn4VcG/0enL1BLAQIUABQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAAAAAAAAAAACAAQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAhQAFAAAAAgAAAAhUGF7L0OJAAAA8gAAAAsAAAAAAAAAAAAAAIAB8wAAAF9yZWxzLy5yZWxzUEsBAhQAFAAAAAgAAAAhUGYYPLiFAAAAtQAAABEAAAAAAAAAAAAAAIABpQEAAHdvcmQvZG9jdW1lbnQueG1sUEsFBgAAAAADAAMAuQAAAFkCAAAAAA==";
    const insertedRange: Word.Range = paragraphRange.insertFileFromBase64(base64File, Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted the embedded document's project update.");
});

insertFootnote(insertText)

插入脚注。 脚注引用放置在区域之后。

insertFootnote(insertText?: string): Word.NoteItem;

参数

insertText

string

可选。 要插入脚注正文的文本。 默认值为 “”。

返回

注解

API 集:WordApi 1.5

示例

// 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.");
});

insertGeometricShape(geometricShapeType, insertShapeOptions)

在文本前面插入几何形状,定位点位于区域的开头。

insertGeometricShape(geometricShapeType: Word.GeometricShapeType, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

参数

geometricShapeType
Word.GeometricShapeType

要插入的形状的几何类型。

insertShapeOptions
Word.InsertShapeOptions

可选。 几何形状的位置和大小。 默认位置和大小 (0、0、100、100) 。

返回

注解

API 集:WordApiDesktop 1.2

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-geometric-shapes.yaml

await Word.run(async (context) => {
  // Inserts a moon geometric shape at the beginning of the selection.
  const selection: Word.Range = context.document.getSelection();
  const shapeOptions: Word.InsertShapeOptions = {
    height: 120,
    width: 120,
    left: 120,
  };
  selection.insertGeometricShape(Word.GeometricShapeType.moon, shapeOptions);
  await context.sync();

  console.log("Inserted a moon.");
});

insertGeometricShape(geometricShapeType, insertShapeOptions)

在文本前面插入几何形状,定位点位于区域的开头。

insertGeometricShape(geometricShapeType: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus", insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

参数

geometricShapeType

"LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus"

要插入的形状的几何类型。

insertShapeOptions
Word.InsertShapeOptions

可选。 几何形状的位置和大小。 默认位置和大小 (0、0、100、100) 。

返回

注解

API 集:WordApiDesktop 1.2

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、beforeendstart或 。after

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph's content with formatted HTML.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const insertedRange: Word.Range = paragraphRange.insertHtml("<b>Project update:</b> <i>ready for review.</i>", Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted bold and italic text from HTML.");
});

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、beforeendstart或 。after

返回

注解

API 集:WordApi 1.2

示例

// 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);
});

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、beforeendstart或 。after

返回

注解

API 集:WordApi 1.1

如果要插入的内容包含链接的内容或外部内容,则不支持插入。 如果是这样,此方法将返回错误 InvalidArgument 。

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph with a bold paragraph from an OOXML package.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const ooxml: string =
        `<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: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:r><w:rPr><w:b/></w:rPr><w:t>Project update from OOXML.</w:t></w:r></w:p></w:body>
                </w:document></pkg:xmlData>
            </pkg:part>
        </pkg:package>`;
    const insertedRange: Word.Range = paragraphRange.insertOoxml(ooxml, Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted a bold paragraph from OOXML.");
});

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

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

参数

paragraphText

string

要插入的段落文本。

insertLocation

before | after | "Before" | "After"

值必须为 OR 。beforeafter

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Adds a paragraph after the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const newParagraph: Word.Paragraph = paragraphRange.insertParagraph("Additional project details.", Word.InsertLocation.after);
    await context.sync();
    console.log("Inserted a paragraph after the summary.");
});

insertPictureFromBase64(base64EncodedImage, insertShapeOptions)

在文本前面插入浮动图片,其定位点位于区域的开头。

insertPictureFromBase64(base64EncodedImage: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

参数

base64EncodedImage

string

要插入的 Base64 编码的图像。

insertShapeOptions
Word.InsertShapeOptions

可选。 图片的位置和大小。 默认位置为 (0, 0) ,默认大小是图像的原始大小。

返回

注解

API 集:WordApiDesktop 1.2

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-inspect-floating-pictures-desktop.yaml

// Anchors a floating picture at the start of the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const pictureOptions: Word.InsertShapeOptions = { left: 20, top: 20, width: 90, height: 39 };
    const picture: Word.Shape = paragraphRange.insertPictureFromBase64(
        "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC",
        pictureOptions
    );
    picture.name = "FloatingPictureSample";
    await context.sync();
    console.log("Inserted a floating picture anchored to the first paragraph. Get anchored shapes to inspect it.");
});

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

表格的列数。

insertLocation

before | after | "Before" | "After"

值必须为 OR 。beforeafter

values

string[][]

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

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Adds a project status table after the last paragraph range.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    const projectTable: Word.Table = lastRange.insertTable(2, 2, Word.InsertLocation.after, [
        ["Task", "Status"],
        ["Review", "Ready"]
    ]);
    await context.sync();
    console.log("Inserted a project status table.");
});

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、beforeendstart或 。after

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Replaces the first paragraph's text without replacing its paragraph mark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const insertedRange: Word.Range = paragraphRange.insertText("Updated project summary.", Word.InsertLocation.replace);
    await context.sync();
    console.log("Replaced the first paragraph's text.");
});

insertTextBox(text, insertShapeOptions)

在文本前面插入浮动文本框,其定位点位于区域的开头。

insertTextBox(text?: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

参数

text

string

可选。 要插入文本框中的文本。

insertShapeOptions
Word.InsertShapeOptions

可选。 文本框的位置和大小。 默认位置和大小 (0、0、100、100) 。

返回

注解

API 集:WordApiDesktop 1.2

示例

// 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 text box at the beginning of the selection.
  const range: Word.Range = context.document.getSelection();
  const insertShapeOptions: Word.InsertShapeOptions = {
    top: 0,
    left: 0,
    height: 100,
    width: 100
  };

  const newTextBox: Word.Shape = range.insertTextBox("placeholder text", insertShapeOptions);
  await context.sync();

  console.log("Inserted a text box at the beginning of the current selection.");
});

intersectWith(range)

返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果两个范围不重叠或不相邻,则引发 ItemNotFound 错误。

intersectWith(range: Word.Range): Word.Range;

参数

range
Word.Range

另一个范围。

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Gets the overlap between the document body and its first paragraph.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const overlap: Word.Range = bodyRange.intersectWith(firstRange);
    overlap.load("text");
    await context.sync();
    console.log(`Overlapping text: ${overlap.text}`);
});

intersectWithOrNullObject(range)

返回新 range 作为此 range 与另一 range 的交集。 此范围不会更改。 如果这两个区域不重叠或不相邻,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性。

intersectWithOrNullObject(range: Word.Range): Word.Range;

参数

range
Word.Range

另一个范围。

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Checks whether the selection overlaps the first paragraph.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const selection: Word.Range = context.document.getSelection();
    const overlap: Word.Range = firstRange.intersectWithOrNullObject(selection);
    overlap.load("text");
    await context.sync();
    if (overlap.isNullObject) {
        console.warn("The selection does not overlap or adjoin the first paragraph.");
        return;
    }
    console.log(`Overlapping text: ${overlap.text}`);
});

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()

删除由该 highlight 方法添加的突出显示(如果有)。

removeHighlight(): void;

返回

void

注解

API 集:WordApi 1.8

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Removes the temporary highlight from the final paragraph.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    lastRange.removeHighlight();
    await context.sync();
    console.log("Removed the temporary highlight.");
});

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; }

可选。 用于搜索的选项。

返回

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Finds whole-word matches within the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const searchOptions: Word.SearchOptions = Word.SearchOptions.newObject(context);
    searchOptions.matchCase = false;
    searchOptions.matchWholeWord = true;
    const matches: Word.RangeCollection = paragraphRange.search("project", searchOptions);
    matches.load("items/text");
    await context.sync();
    console.log(`Matches found: ${matches.items.length}`);
    matches.items.forEach((match: Word.Range) => console.log(match.text));
});

select(selectionMode)

选择并在 Word UI 中导航到区域。

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

参数

selectionMode
Word.SelectionMode

可选。 选择模式必须为 select、 、start 或 end。 select 为默认值。

返回

void

注解

API 集:WordApi 1.1

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Selects the final paragraph and scrolls it into view.
await Word.run(async (context) => {
  const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
  lastRange.select();

  await context.sync();
});

select(selectionMode)

选择并在 Word UI 中导航到区域。

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

参数

selectionMode

"Select" | "Start" | "End"

可选。 选择模式必须为 select、 、start 或 end。 select 为默认值。

返回

void

注解

API 集:WordApi 1.1

set(properties, options)

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

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

参数

properties
Word.Interfaces.RangeUpdateData

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

options
OfficeExtension.UpdateOptions

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

返回

void

set(properties)

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

set(properties: Word.Range): void;

参数

properties
Word.Range

返回

void

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将相应范围拆分为各个子范围。

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

参数

delimiters

string[]

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

multiParagraphs

boolean

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

trimDelimiters

boolean

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

trimSpacing

boolean

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

返回

注解

API 集:WordApi 1.3

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Splits the first paragraph into words and highlights them in sequence.
await Word.run(async (context) => {
  const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
  const words: Word.RangeCollection = paragraphRange.split([" "], false, true, true);
  words.load("text");

  await context.sync();

  for (let i = 0; i < words.items.length; i++) {
    if (i >= 1) {
      words.items[i - 1].font.highlightColor = "#FFFFFF";
    }
    words.items[i].font.highlightColor = "#FFFF00";

    await context.sync();
    await new Promise((resolve) => setTimeout(resolve, 200));
  }
});

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;

返回

事件详细信息

onCommentAdded

注意

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

在添加新批注时发生。

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

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentChanged

注意

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

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

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

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentDeselected

注意

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

取消选择批注时出现。

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

事件类型

注解

API 集:WordApi BETA (仅预览版)

onCommentSelected

注意

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

选中批注时出现。

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

事件类型

注解

API 集:WordApi BETA (仅预览版)