Word.Range class

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

Extends

注解

[ API 集:WordApi 1.1 ]

属性

contentControls

获取区域中的内容控件对象的集合。

context

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

font

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

paragraphs

获取区域中的段落对象的集合。

parentContentControl

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

style

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

text

获取区域的文本。

方法

clear()

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

delete()

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

getHtml()

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

getOoxml()

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

insertBreak(breakType, insertLocation)

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

insertContentControl(contentControlType)

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

insertFileFromBase64(base64File, insertLocation)

在指定位置插入 document。

insertHtml(html, insertLocation)

在指定位置插入 HTML。

insertOoxml(ooxml, insertLocation)

在指定位置插入 OOXML。

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertText(text, insertLocation)

在指定位置插入文本。

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

search(searchText, searchOptions)

对范围对象的范围使用指定的 SearchOptions 执行搜索。 搜索结果是 range 对象的集合。

select(selectionMode)

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

select(selectionModeString)

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

set(properties, options)

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

set(properties)

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

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

属性详细信息

contentControls

获取区域中的内容控件对象的集合。

readonly contentControls: Word.ContentControlCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

context

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

context: RequestContext;

属性值

font

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

readonly font: Word.Font;

属性值

注解

[ API 集:WordApi 1.1 ]

paragraphs

获取区域中的段落对象的集合。

readonly paragraphs: Word.ParagraphCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

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

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

style

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

style: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

text

获取区域的文本。

readonly text: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

方法详细信息

clear()

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

clear(): void;

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to clear the contents of the proxy range object.
    range.clear();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Cleared the selection (range object)');
});

delete()

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

delete(): void;

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to delete the range object.
    range.delete();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Deleted the selection (range object)');
});

getHtml()

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

getHtml(): OfficeExtension.ClientResult<string>;

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to get the HTML of the current selection.
    const html = range.getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('The HTML read from the document was: ' + html.value);
});

getOoxml()

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

getOoxml(): OfficeExtension.ClientResult<string>;

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to get the OOXML of the current selection.
    const ooxml = range.getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('The OOXML read from the document was:  ' + ooxml.value);
});

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"

必填。 该值必须为“Before”或“After”。

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert a page break after the selected text.
    range.insertBreak(Word.BreakType.page, Word.InsertLocation.after);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted a page break after the selected text.');
});

insertContentControl(contentControlType)

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

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | "RichText" | "PlainText" | "CheckBox"): Word.ContentControl;

参数

contentControlType

richText | plainText | checkBox | "RichText" | "PlainText" | "CheckBox"

可选。 要插入的内容控件类型。 必须为“RichText”、“PlainText”或“CheckBox”。 默认值为“RichText”。

返回

注解

[ API 集:WordApi 1.1 ]

注意:参数 contentControlType 是在 WordApi 1.5 中引入的。 PlainText 支持已在 WordApi 1.5 中添加。 CheckBox 支持已在 WordApi 1.7 中添加。

示例

// 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 = context.document.body.search("Contractor");
    results.load("font/bold");

    // Check to make sure these content controls haven't been added yet.
    const customerContentControls = 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 = 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();
});

insertFileFromBase64(base64File, insertLocation)

在指定位置插入 document。

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

参数

base64File

string

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

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

返回

注解

[ API 集:WordApi 1.1 ]

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

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert base64 encoded .docx at the beginning of the range.
    // You'll need to implement getBase64() to make this work.
    range.insertFileFromBase64(getBase64(), Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Added base64 encoded text to the beginning of the range.');
});

insertHtml(html, insertLocation)

在指定位置插入 HTML。

insertHtml(html: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

参数

html

string

必填。 要插入的 HTML。

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert HTML in to the beginning of the range.
    range.insertHtml('<strong>This is text inserted with range.insertHtml()</strong>', Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('HTML added to the beginning of the range.');
});

insertOoxml(ooxml, insertLocation)

在指定位置插入 OOXML。

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

参数

ooxml

string

必填。 要插入的 OOXML。

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert OOXML in to the beginning of the range.
    range.insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('OOXML added to the beginning of the range.');
});

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

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

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

参数

paragraphText

string

必填。 要插入的段落文本。

insertLocation

before | after | "Before" | "After"

必填。 该值必须为“Before”或“After”。

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert the paragraph after the range.
    range.insertParagraph('Content of a new paragraph', Word.InsertLocation.after);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph added to the end of the range.');
});

insertText(text, insertLocation)

在指定位置插入文本。

insertText(text: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

参数

text

string

必填。 要插入的文本。

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

返回

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert the paragraph at the end of the range.
    range.insertText('New text inserted into the range.', Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Text added to the end of the range.');
});

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 一个逗号分隔的字符串,指定要加载的导航属性。

返回

search(searchText, searchOptions)

对范围对象的范围使用指定的 SearchOptions 执行搜索。 搜索结果是 range 对象的集合。

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

参数

searchText

string

必填。 搜索文本。

searchOptions

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

可选。 用于搜索的选项。

返回

注解

[ API 集:WordApi 1.1 ]

select(selectionMode)

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

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

参数

selectionMode
Word.SelectionMode

可选。 选择模式必须为“Select”、“Start”或“End”。 “Select”为默认值。

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert HTML in to the beginning of the range.
    range.insertHtml('<strong>This is text inserted with range.insertHtml()</strong>', Word.InsertLocation.start);

    // Queue a command to select the HTML that was inserted.
    range.select();

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

select(selectionModeString)

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

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

参数

selectionModeString

"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

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;

返回