Class Table

Стол

Элемент, представляющий таблицу. Table может содержать только элементы Table Row . Для получения дополнительной информации о структуре документа см. руководство по расширению Google Docs .

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

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Create a two-dimensional array containing the cell contents.
const cells = [
  ['Row 1, Cell 1', 'Row 1, Cell 2'],
  ['Row 2, Cell 1', 'Row 2, Cell 2'],
];

// Build a table from the array.
body.appendTable(cells);

Методы

Метод Тип возвращаемого значения Краткое описание
append Table Row() Table Row Создает и добавляет новую Table Row .
append Table Row(tableRow) Table Row Добавляет указанную Table Row .
clear() Table Очищает содержимое элемента.
copy() Table Возвращает отсоединенную, глубокую копию текущего элемента.
edit As Text() Text Получает Text версию текущего элемента для редактирования.
find Element(elementType) Range Element |null Выполняет поиск в содержимом элемента потомка указанного типа.
find Element(elementType, from) Range Element |null Выполняет поиск в содержимом элемента потомка указанного типа, начиная с указанного Range Element .
find Text(searchPattern) Range Element |null Выполняет поиск указанного текстового шаблона в содержимом элемента с использованием регулярных выражений.
find Text(searchPattern, from) Range Element |null Выполняет поиск указанного текстового шаблона в содержимом элемента, начиная с заданного результата поиска.
get Attributes() Object Получает атрибуты элемента.
get Border Color() String|null Получает цвет границы.
get Border Width() Number|null Извлекает ширину границы в пунктах.
get Cell(rowIndex, cellIndex) Table Cell |null Извлекает Table Cell по указанным индексам строки и ячейки.
get Child(childIndex) Element Извлекает дочерний элемент по указанному индексу дочернего элемента.
get Child Index(child) Integer Получает индекс дочернего элемента для указанного дочернего элемента.
get Column Width(columnIndex) Number|null Извлекает ширину указанного столбца таблицы в пунктах.
get Link Url() String|null Получает URL-адрес ссылки.
get Next Sibling() Element |null Получает следующий соседний элемент.
get Num Children() Integer Получает количество детей.
get Num Rows() Integer Получает количество Table Rows .
get Parent() Container Element |null Получает родительский элемент элемента.
get Previous Sibling() Element |null Получает предыдущий соседний элемент.
get Row(rowIndex) Table Row |null Извлекает Table Row по указанному индексу.
get Text() String Извлекает содержимое элемента в виде текстовой строки.
get Text Alignment() Text Alignment |null Получает выравнивание текста.
get Type() Element Type Получает Element Type элемента.
insert Table Row(childIndex) Table Row Создает и вставляет новую Table Row по указанному индексу.
insert Table Row(childIndex, tableRow) Table Row Вставляет указанную Table Row по указанному индексу.
is At Document End() Boolean Определяет, находится ли элемент в конце Document .
remove Child(child) Table Удаляет указанный дочерний элемент.
remove From Parent() Table |null Удаляет элемент из родительского элемента.
remove Row(rowIndex) Table Row Удаляет Table Row по указанному индексу.
replace Text(searchPattern, replacement) Element Заменяет все вхождения заданного текстового шаблона заданной строкой замены, используя регулярные выражения.
set Attributes(attributes) Table Задает атрибуты элемента.
set Border Color(color) Table Задает цвет границы.
set Border Width(width) Table Задает ширину границы в пунктах.
set Column Width(columnIndex, width) Table Задает ширину указанного столбца в пунктах.
set Link Url(url) Table Задает URL-адрес ссылки.
set Text Alignment(textAlignment) Table Задает выравнивание текста.

Подробная документация

append Table Row()

Создает и добавляет новую Table Row .

Возвращаться

Table Row — новый элемент строки таблицы

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

append Table Row(tableRow)

Добавляет указанную Table Row .

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table in the tab and copies the second row.
const table = body.getTables()[0];
const row = table.getChild(1).copy();

// Adds the copied row to the bottom of the table.
const tableRow = table.appendTableRow(row);

Параметры

Имя Тип Описание
table Row Table Row Строка таблицы, которую нужно добавить.

Возвращаться

Table Row — элемент, добавляемый в строку таблицы.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

clear()

Очищает содержимое элемента.

Возвращаться

Table — Текущий элемент.


copy()

Возвращает отсоединенную, глубокую копию текущего элемента.

Все дочерние элементы, присутствующие в новом элементе, также копируются. У нового элемента нет родителя.

Возвращаться

Table — Новый экземпляр.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

edit As Text()

Получает Text версию текущего элемента для редактирования.

Используйте режим edit As Text для преобразования содержимого элементов в форматированный текст. edit As Text режиме игнорируются нетекстовые элементы (например, Inline Image и Horizontal Rule ).

Дочерние элементы, полностью находящиеся в пределах удаленного текстового диапазона, удаляются из элемента.

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Insert two paragraphs separated by a paragraph containing an
// horizontal rule.
body.insertParagraph(0, 'An editAsText sample.');
body.insertHorizontalRule(0);
body.insertParagraph(0, 'An example.');

// Delete " sample.\n\n An" removing the horizontal rule in the process.
body.editAsText().deleteText(14, 25);

Возвращаться

Text — текстовая версия текущего элемента


find Element(elementType)

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

Параметры

Имя Тип Описание
element Type Element Type Тип элемента для поиска.

Возвращаться

Range Element |null — Результат поиска, указывающий позицию искомого элемента.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

find Element(elementType, from)

Выполняет поиск в содержимом элемента потомка указанного типа, начиная с указанного Range Element .

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Define the search parameters.

let searchResult = null;

// Search until the paragraph is found.
while (
    (searchResult = body.findElement(
         DocumentApp.ElementType.PARAGRAPH,
         searchResult,
         ))) {
  const par = searchResult.getElement().asParagraph();
  if (par.getHeading() === DocumentApp.ParagraphHeading.HEADING1) {
    // Found one, update and stop.
    par.setText('This is the first header.');
    break;
  }
}

Параметры

Имя Тип Описание
element Type Element Type Тип элемента для поиска.
from Range Element Результаты поиска, из которых следует начинать поиск.

Возвращаться

Range Element |null — Результат поиска, указывающий следующую позицию искомого элемента.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

find Text(searchPattern)

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

Некоторые функции регулярных выражений JavaScript поддерживаются не в полной мере, например, группы захвата и модификаторы режима.

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

Параметры

Имя Тип Описание
search Pattern String шаблон для поиска

Возвращаться

Range Element |null — результат поиска, указывающий позицию искомого текста, или null, если совпадений нет.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

find Text(searchPattern, from)

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

Некоторые функции регулярных выражений JavaScript поддерживаются не в полной мере, например, группы захвата и модификаторы режима.

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

Параметры

Имя Тип Описание
search Pattern String шаблон для поиска
from Range Element Результаты поиска, из которых следует осуществлять поиск.

Возвращаться

Range Element |null — результат поиска, указывающий следующую позицию искомого текста, или null, если совпадений нет.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Attributes()

Получает атрибуты элемента.

В результате получается объект, содержащий свойство для каждого допустимого атрибута элемента, где каждое имя свойства соответствует элементу в перечислении Document App.Attribute .

const doc = DocumentApp.getActiveDocument();
const documentTab = doc.getActiveTab().asDocumentTab();
const body = documentTab.getBody();

// Append a styled paragraph.
const par = body.appendParagraph('A bold, italicized paragraph.');
par.setBold(true);
par.setItalic(true);

// Retrieve the paragraph's attributes.
const atts = par.getAttributes();

// Log the paragraph attributes.
for (const att in atts) {
  Logger.log(`${att}:${atts[att]}`);
}

Возвращаться

Object — Атрибуты элемента.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Border Color()

Получает цвет границы.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Sets the border color of the first table.
table.setBorderColor('#00FF00');

// Logs the border color of the first table to the console.
console.log(table.getBorderColor());

Возвращаться

String|null — Цвет границы, заданный в формате CSS (например '#ffffff' ).

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Border Width()

Извлекает ширину границы в пунктах.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Sets the border width of the first table.
table.setBorderWidth(20);

// Logs the border width of the first table.
console.log(table.getBorderWidth());

Возвращаться

Number|null — Ширина границы в пунктах.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Cell(rowIndex, cellIndex)

Извлекает Table Cell по указанным индексам строки и ячейки.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Gets the cell of the table's third row and second column.
const cell = table.getCell(2, 1);

// Logs the cell text to the console.
console.log(cell.getText());

Параметры

Имя Тип Описание
row Index Integer Индекс строки, содержащей ячейку, которую необходимо извлечь.
cell Index Integer Индекс ячейки, которую необходимо извлечь.

Возвращаться

Table Cell |null — Ячейка таблицы.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Child(childIndex)

Извлекает дочерний элемент по указанному индексу дочернего элемента.

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Obtain the first element in the tab.
const firstChild = body.getChild(0);

// If it's a paragraph, set its contents.
if (firstChild.getType() === DocumentApp.ElementType.PARAGRAPH) {
  firstChild.asParagraph().setText('This is the first paragraph.');
}

Параметры

Имя Тип Описание
child Index Integer Индекс дочернего элемента, который необходимо получить.

Возвращаться

Element — дочерний элемент по указанному индексу.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Child Index(child)

Получает индекс дочернего элемента для указанного дочернего элемента.

Параметры

Имя Тип Описание
child Element Дочерний элемент, для которого необходимо получить индекс.

Возвращаться

Integer — дочерний индекс.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Column Width(columnIndex)

Извлекает ширину указанного столбца таблицы в пунктах.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Sets the width of the second column to 100 points.
const columnWidth = table.setColumnWidth(1, 100);

// Gets the width of the second column and logs it to the console.
console.log(columnWidth.getColumnWidth(1));

Параметры

Имя Тип Описание
column Index Integer Указатель столбцов.

Возвращаться

Number|null — Ширина столбца в пунктах.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Link Url()

Получает URL-адрес ссылки.

Возвращаться

String|null — URL ссылки, или null, если элемент содержит несколько значений для этого атрибута.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Next Sibling()

Получает следующий соседний элемент.

Следующий элемент-близнец имеет того же родителя и следует за текущим элементом.

Возвращаться

Element |null — Следующий соседний элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Num Children()

Получает количество детей.

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Log the number of elements in the tab.
Logger.log(`There are ${body.getNumChildren()} elements in the tab's body.`);

Возвращаться

Integer — количество детей.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Num Rows()

Получает количество Table Rows .

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Logs the number of rows of the first table to the console.
console.log(table.getNumRows());

Возвращаться

Integer — количество строк в таблице.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Parent()

Получает родительский элемент элемента.

Родительский элемент содержит текущий элемент.

Возвращаться

Container Element |null — Родительский элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Previous Sibling()

Получает предыдущий соседний элемент.

Предыдущий соседний элемент имеет того же родителя и предшествует текущему элементу.

Возвращаться

Element |null — Предыдущий соседний элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Row(rowIndex)

Извлекает Table Row по указанному индексу.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table and logs the text of first row to the console.
const table = body.getTables()[0];
console.log(table.getRow(0).getText());

Параметры

Имя Тип Описание
row Index Integer Индекс строки, которую необходимо извлечь.

Возвращаться

Table Row |null — Строка таблицы.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Text()

Извлекает содержимое элемента в виде текстовой строки.

Возвращаться

String — содержимое элемента в виде текстовой строки.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Text Alignment()

Получает выравнивание текста. Доступные типы выравнивания: Document App.TextAlignment.NORMAL , Document App.TextAlignment.SUBSCRIPT и Document App.TextAlignment.SUPERSCRIPT .

Возвращаться

Text Alignment |null — тип выравнивания текста, или null если текст содержит несколько типов выравнивания или если выравнивание текста никогда не было задано.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

get Type()

Получает Element Type элемента.

Используйте get Type() , чтобы определить точный тип заданного элемента.

const doc = DocumentApp.getActiveDocument();
const documentTab = doc.getActiveTab().asDocumentTab();
const body = documentTab.getBody();

// Obtain the first element in the active tab's body.

const firstChild = body.getChild(0);

// Use getType() to determine the element's type.
if (firstChild.getType() === DocumentApp.ElementType.PARAGRAPH) {
  Logger.log('The first element is a paragraph.');
} else {
  Logger.log('The first element is not a paragraph.');
}

Возвращаться

Element Type — Тип элемента.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

insert Table Row(childIndex)

Создает и вставляет новую Table Row по указанному индексу.

Параметры

Имя Тип Описание
child Index Integer индекс, по которому следует вставить элемент

Возвращаться

Table Row — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

insert Table Row(childIndex, tableRow)

Вставляет указанную Table Row по указанному индексу.

Параметры

Имя Тип Описание
child Index Integer индекс, по которому следует вставить элемент
table Row Table Row строка таблицы для вставки

Возвращаться

Table Row — вставляемый элемент строки таблицы.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

is At Document End()

Определяет, находится ли элемент в конце Document .

Возвращаться

Boolean — указывает, находится ли элемент в конце вкладки.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

remove Child(child)

Удаляет указанный дочерний элемент.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Finds the first table row and removes it.
const element = table.findElement(DocumentApp.ElementType.TABLE_ROW);
table.removeChild(element.getElement());

Параметры

Имя Тип Описание
child Element Дочерний элемент, который нужно удалить.

Возвращаться

Table — Текущий элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

remove From Parent()

Удаляет элемент из родительского элемента.

const doc = DocumentApp.getActiveDocument();
const documentTab = doc.getActiveTab().asDocumentTab();
const body = documentTab.getBody();

// Remove all images in the active tab's body.
const imgs = body.getImages();
for (let i = 0; i < imgs.length; i++) {
  imgs[i].removeFromParent();
}

Возвращаться

Table |null — Удаленный элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

remove Row(rowIndex)

Удаляет Table Row по указанному индексу.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table and removes its second row.
const table = body.getTables()[0];
table.removeRow(1);

Параметры

Имя Тип Описание
row Index Integer Индекс строки, которую нужно удалить.

Возвращаться

Table Row — Удалённая строка.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

replace Text(searchPattern, replacement)

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

Шаблон поиска передается в виде строки, а не объекта регулярного выражения JavaScript. Поэтому вам потребуется экранировать все обратные косые черты в шаблоне.

Этот метод использует библиотеку регулярных выражений RE2 от Google, что ограничивает поддерживаемый синтаксис .

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

const body =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

// Clear the text surrounding "Apps Script", with or without text.
body.replaceText('^.*Apps ?Script.*$', 'Apps Script');

Параметры

Имя Тип Описание
search Pattern String шаблон регулярного выражения для поиска
replacement String текст, который следует использовать в качестве замены

Возвращаться

Element — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Attributes(attributes)

Задает атрибуты элемента.

Указанный параметр attributes должен представлять собой объект, где каждое имя свойства является элементом перечисления Document App.Attribute , а каждое значение свойства — новым значением, которое должно быть применено.

const doc = DocumentApp.getActiveDocument();
const documentTab = doc.getActiveTab().asDocumentTab();
const body = documentTab.getBody();

// Define a custom paragraph style.
const style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
    DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.FONT_SIZE] = 18;
style[DocumentApp.Attribute.BOLD] = true;

// Append a plain paragraph.
const par = body.appendParagraph('A paragraph with custom style.');

// Apply the custom style.
par.setAttributes(style);

Параметры

Имя Тип Описание
attributes Object Атрибуты элемента.

Возвращаться

Table — Текущий элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Border Color(color)

Задает цвет границы.

// Opens the Docs file by its ID. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the ID with your own.
const doc = DocumentApp.openById('123abc');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab('123abc').asDocumentTab().getBody();

// Gets the first table.
const table = body.getTables()[0];

// Sets the border color of the table to green.
table.setBorderColor('#00FF00');

Параметры

Имя Тип Описание
color String Цвет границы, заданный в формате CSS (например '#ffffff' ).

Возвращаться

Table — Текущий элемент.

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Border Width(width)

Задает ширину границы в пунктах.

Параметры

Имя Тип Описание
width Number ширина границы в пунктах

Возвращаться

Table — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Column Width(columnIndex, width)

Задает ширину указанного столбца в пунктах.

Параметры

Имя Тип Описание
column Index Integer указатель столбцов
width Number ширина границы в пунктах

Возвращаться

Table — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Link Url(url)

Задает URL-адрес ссылки.

Параметры

Имя Тип Описание
url String URL-адрес ссылки

Возвращаться

Table — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

set Text Alignment(textAlignment)

Задает выравнивание текста. Доступные типы выравнивания: Document App.TextAlignment.NORMAL , Document App.TextAlignment.SUBSCRIPT и Document App.TextAlignment.SUPERSCRIPT .

// Make the entire first paragraph in the active tab be superscript.
const documentTab =
    DocumentApp.getActiveDocument().getActiveTab().asDocumentTab();
const text = documentTab.getBody().getParagraphs()[0].editAsText();
text.setTextAlignment(DocumentApp.TextAlignment.SUPERSCRIPT);

Параметры

Имя Тип Описание
text Alignment Text Alignment тип выравнивания текста, который следует применить

Возвращаться

Table — текущий элемент

Авторизация

Для скриптов, использующих этот метод, требуется авторизация в одной или нескольких из следующих областей действия :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents