Поделиться через


Word.Range class

Представляет непрерывную область в документе.

Extends

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

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

// Gets the range of the first comment in the selected content.
await Word.run(async (context) => {
  const comment: Word.Comment = context.document.getSelection().getComments().getFirstOrNullObject();
  comment.load("contentRange");
  const range: Word.Range = comment.getRange();
  range.load("text");
  await context.sync();

  if (comment.isNullObject) {
    console.warn("No comments in the selection, so no range to get.");
    return;
  }

  console.log(`Comment location: ${range.text}`);
  const contentRange: Word.CommentContentRange = comment.contentRange;
  console.log("Comment content range:", contentRange);
});

Свойства

contentControls

Возвращает коллекцию объектов элементов управления содержимым в диапазоне.

context

Контекст запроса, связанный с объектом . Это соединяет процесс надстройки с процессом ведущего приложения Office.

font

Возвращает формат текста диапазона. Используйте это свойство, чтобы получать и задавать имея, размер, цвет и другие свойства шрифта.

inlinePictures

Возвращает коллекцию объектов встроенных рисунков в диапазоне.

paragraphs

Возвращает коллекцию объектов абзаца в диапазоне.

parentContentControl

Возвращает поддерживаемый в настоящее время элемент управления содержимым, содержащий диапазон. Выдает ошибку ItemNotFound , если родительского элемента управления содержимым нет.

style

Задает имя стиля для диапазона. Используйте это свойство для пользовательских стилей и локализованных имен стилей. Чтобы использовать встроенные стили, поддерживающие несколько языковых стандартов, применяйте свойство styleBuiltIn.

text

Возвращает текст диапазона.

Методы

clear()

Очищает содержимое объекта диапазона. Пользователь может отменить операцию для очищенного содержимого.

delete()

Удаляет диапазон и его содержимое из документа.

getHtml()

Возвращает HTML-представление объекта диапазона. При отображении на веб-странице или в средстве просмотра HTML форматирование будет близко, но не точно совпадает с форматированием документа. Этот метод не возвращает один и тот же HTML-код для одного документа на разных платформах (Windows, Mac, Word в Интернете и т. д.). Если вам нужна точную точность или согласованность на разных платформах, используйте Range.getOoxml() и преобразуйте возвращенный XML-код в HTML.

getOoxml()

Возвращает OOXML-представление объекта диапазона.

insertBreak(breakType, insertLocation)

Вставляет разрыв в указанном расположении в основном документе.

insertContentControl(contentControlType)

Заключает объект Range в элемент управления содержимым.

insertFileFromBase64(base64File, insertLocation)

Вставляет документ в указанном расположении.

insertHtml(html, insertLocation)

Вставляет HTML-код в указанном расположении.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Вставляет рисунок в указанном расположении.

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 в области объекта диапазона. Результат поиска — это коллекция объектов диапазона.

select(selectionMode)

Выбор диапазона и переход к нему в пользовательском интерфейсе Word.

select(selectionModeString)

Выбор диапазона и переход к нему в пользовательском интерфейсе Word.

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 ]

inlinePictures

Возвращает коллекцию объектов встроенных рисунков в диапазоне.

readonly inlinePictures: Word.InlinePictureCollection;

Значение свойства

Комментарии

[ Набор API: WordApi 1.2 ]

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

style

Задает имя стиля для диапазона. Используйте это свойство для пользовательских стилей и локализованных имен стилей. Чтобы использовать встроенные стили, поддерживающие несколько языковых стандартов, применяйте свойство styleBuiltIn.

style: string;

Значение свойства

string

Комментарии

[ Набор API: WordApi 1.1 ]

text

Возвращает текст диапазона.

readonly text: string;

Значение свойства

string

Комментарии

[ Набор API: WordApi 1.1 ]

Сведения о методе

clear()

Очищает содержимое объекта диапазона. Пользователь может отменить операцию для очищенного содержимого.

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

Возвращает HTML-представление объекта диапазона. При отображении на веб-странице или в средстве просмотра HTML форматирование будет близко, но не точно совпадает с форматированием документа. Этот метод не возвращает один и тот же HTML-код для одного документа на разных платформах (Windows, Mac, 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()

Возвращает 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"

Обязательно. Значение должно быть "До" или "После".

Возвращаемое значение

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

insertFileFromBase64(base64File, insertLocation)

Вставляет документ в указанном расположении.

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

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Вставляет рисунок в указанном расположении.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.InlinePicture;

Параметры

base64EncodedImage

string

Обязательно. Вставляемый образ в кодировке Base64.

insertLocation

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

Обязательно. Значение должно быть "Replace", "Start", "End", "Before" или "After".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.2 ]

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"

Обязательно. Значение должно быть "До" или "После".

Возвращаемое значение

Комментарии

[ Набор 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 в области объекта диапазона. Результат поиска — это коллекция объектов диапазона.

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.

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.

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

Предоставляет возможность подавления ошибок, если объект свойств пытается задать какие-либо свойства, доступные только для чтения.

Возвращаемое значение

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;

Возвращаемое значение