Class Range

Диапазон

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

Методы

Метод Тип возвращаемого значения Краткое описание
activate() Range Устанавливает указанный диапазон в качестве active range , при этом верхняя левая ячейка в диапазоне является current cell .
activate As Current Cell() Range Устанавливает указанную ячейку в качестве current cell .
add Developer Metadata(key) Range Добавляет метаданные разработчика с указанным ключом в диапазон.
add Developer Metadata(key, visibility) Range Добавляет метаданные разработчика с указанным ключом и уровнем видимости в заданный диапазон.
add Developer Metadata(key, value) Range Добавляет метаданные разработчика с указанным ключом и значением в заданный диапазон.
add Developer Metadata(key, value, visibility) Range Добавляет метаданные разработчика с указанным ключом, значением и видимостью в заданный диапазон.
apply Column Banding() Banding Применяет к диапазону тему оформления столбцов по умолчанию.
apply Column Banding(bandingTheme) Banding Применяет заданную тему полосового оформления столбцов к диапазону.
apply Column Banding(bandingTheme, showHeader, showFooter) Banding Применяет указанную тему полосового оформления столбцов к диапазону с заданными настройками верхнего и нижнего колонтитулов.
apply Row Banding() Banding Применяет к диапазону стандартную тему оформления строк.
apply Row Banding(bandingTheme) Banding Применяет заданную тему полосового отображения строк к диапазону.
apply Row Banding(bandingTheme, showHeader, showFooter) Banding Применяет указанную тему полосового оформления строк к диапазону с заданными настройками верхнего и нижнего колонтитулов.
auto Fill(destination, series) void Заполняет destination Range данными на основе данных, содержащихся в этом диапазоне.
auto Fill To Neighbor(series) void Вычисляет диапазон для заполнения новыми данными на основе соседних ячеек и автоматически заполняет этот диапазон новыми значениями на основе данных, содержащихся в этом диапазоне.
break Apart() Range Разделите все ячейки в диапазоне, содержащие несколько столбцов, на отдельные ячейки.
can Edit() Boolean Определяет, имеет ли пользователь разрешение на редактирование каждой ячейки в диапазоне.
check() Range Изменяет состояние флажков в диапазоне на «отмечено».
clear() Range Очищает диапазон содержимого и форматов.
clear(options) Range Очищает диапазон содержимого, формата, правил проверки данных и/или комментариев в соответствии с заданными расширенными параметрами.
clear Content() Range Очищает содержимое диапазона, сохраняя форматирование.
clear Data Validations() Range Сбрасывает правила проверки данных для указанного диапазона.
clear Format() Range Очищает форматирование для этого диапазона.
clear Note() Range Удаляет примечание в указанной ячейке или ячейках.
collapse Groups() Range Объединяет все группы, которые полностью находятся в пределах указанного диапазона.
copy Format To Range(gridId, column, columnEnd, row, rowEnd) void Скопируйте форматирование диапазона в указанное место.
copy Format To Range(sheet, column, columnEnd, row, rowEnd) void Скопируйте форматирование диапазона в указанное место.
copy To(destination) void Копирует данные из диапазона ячеек в другой диапазон ячеек.
copy To(destination, copyPasteType, transposed) void Копирует данные из диапазона ячеек в другой диапазон ячеек.
copy To(destination, options) void Копирует данные из диапазона ячеек в другой диапазон ячеек.
copy Values To Range(gridId, column, columnEnd, row, rowEnd) void Скопируйте содержимое диапазона в указанное место.
copy Values To Range(sheet, column, columnEnd, row, rowEnd) void Скопируйте содержимое диапазона в указанное место.
create Data Source Pivot Table(dataSource) Data Source Pivot Table Создает пустую сводную таблицу на основе исходных данных, привязанную к первой ячейке в этом диапазоне.
create Data Source Table(dataSource) Data Source Table Создает пустую таблицу источника данных на основе исходных данных, привязанную к первой ячейке в этом диапазоне.
create Developer Metadata Finder() Developer Metadata Finder Возвращает объект DeveloperMetadataFinderApi для поиска метаданных разработчика в пределах указанного диапазона.
create Filter() Filter Создает фильтр и применяет его к указанному диапазону на листе.
create Pivot Table(sourceData) Pivot Table Создает пустую сводную таблицу на основе указанных source Data привязанных к первой ячейке в этом диапазоне.
create Text Finder(findText) Text Finder Создает средство поиска текста для заданного диапазона, которое может находить и заменять текст в этом диапазоне.
delete Cells(shiftDimension) void Удаляет этот диапазон ячеек.
expand Groups() Range Разворачивает свернутые группы, диапазон которых или переключатель управления пересекаются с этим диапазоном.
getA1Notation() String Возвращает строковое описание диапазона в формате A1.
get Background() String Возвращает цвет фона ячейки в верхнем левом углу диапазона (например, '#ffffff' ).
get Background Object() Color Возвращает цвет фона ячейки в верхнем левом углу диапазона.
get Background Objects() Color[][] Возвращает цвет фона ячеек в заданном диапазоне.
get Backgrounds() String[][] Возвращает цвет фона ячеек в заданном диапазоне (например, '#ffffff' ).
get Bandings() Banding[] Возвращает все полосы, примененные к любым ячейкам в этом диапазоне.
get Cell(row, column) Range Возвращает заданную ячейку в указанном диапазоне.
get Column() Integer Возвращает начальную позицию столбца для данного диапазона.
get Data Region() Range Возвращает копию диапазона, расширенного в четырех основных Direction , чтобы охватить все смежные ячейки, содержащие данные.
get Data Region(dimension) Range Возвращает копию развернутого диапазона. Если указанное измерение равно Dimension.ROWS , возвращайте Direction.UP и Direction.DOWN , а если измерение равно Dimension.COLUMNS , Direction.NEXT и Direction.PREVIOUS .
get Data Source Formula() Data Source Formula |null Возвращает Data Source Formula для первой ячейки в диапазоне или null , если ячейка не содержит формулу источника данных.
get Data Source Formulas() Data Source Formula[] Возвращает Data Source Formula для ячеек в заданном диапазоне.
get Data Source Pivot Tables() Data Source Pivot Table[] Получает все сводные таблицы источников данных, пересекающиеся с заданным диапазоном.
get Data Source Tables() Data Source Table[] Получает все таблицы источников данных, пересекающиеся с заданным диапазоном.
get Data Source Url() String Возвращает URL-адрес данных в указанном диапазоне, который можно использовать для создания диаграмм и запросов.
get Data Table() Data Table Возвращает данные из этого объекта в виде DataTable.
get Data Table(firstRowIsHeader) Data Table Верните данные из этого диапазона в виде объекта DataTable.
get Data Validation() Data Validation Возвращает правило проверки данных для ячейки в верхнем левом углу диапазона.
get Data Validations() Data Validation[][] Возвращает правила проверки данных для всех ячеек в заданном диапазоне.
get Developer Metadata() Developer Metadata[] Получает метаданные разработчика, связанные с этим диапазоном.
get Display Value() String Возвращает отображаемое значение ячейки в верхнем левом углу диапазона.
get Display Values() String[][] Возвращает прямоугольную сетку значений для данного диапазона.
get Filter() Filter |null Возвращает фильтр на листе, к которому принадлежит данный диапазон, или null если на листе нет фильтра.
get Font Color Object() Color Возвращает цвет шрифта ячейки в верхнем левом углу диапазона.
get Font Color Objects() Color[][] Возвращает цвет шрифта ячеек в заданном диапазоне.
get Font Families() String[][] Возвращает семейства шрифтов ячеек в заданном диапазоне.
get Font Family() String Возвращает семейство шрифтов ячейки, расположенной в верхнем левом углу диапазона.
get Font Line() String Задает стиль линии ячейки в верхнем левом углу диапазона ( 'underline' , 'line-through' или 'none' ).
get Font Lines() String[][] Получает стиль строки ячеек в диапазоне ( 'underline' , 'line-through' или 'none' ).
get Font Size() Integer Возвращает размер шрифта в пунктах для ячейки в верхнем левом углу диапазона.
get Font Sizes() Integer[][] Возвращает размеры шрифтов ячеек в заданном диапазоне.
get Font Style() String Возвращает стиль шрифта ( 'italic' или 'normal' ) ячейки в верхнем левом углу диапазона.
get Font Styles() String[][] Возвращает стили шрифтов ячеек в заданном диапазоне.
get Font Weight() String Возвращает толщину шрифта (обычный/жирный) ячейки в верхнем левом углу диапазона.
get Font Weights() String[][] Возвращает толщину шрифта ячеек в заданном диапазоне.
get Formula() String Возвращает формулу (в формате A1) для ячейки в верхнем левом углу диапазона или пустую строку, если ячейка пуста или не содержит формулы.
get Formula R1C1() String Возвращает формулу (в формате R1C1) для заданной ячейки или null , если формула отсутствует.
get Formulas() String[][] Возвращает формулы (в формате A1) для ячеек в заданном диапазоне.
get Formulas R1C1() String[][] Возвращает формулы (в формате R1C1) для ячеек в заданном диапазоне.
get Grid Id() Integer Возвращает идентификатор сетки родительского листа диапазона.
get Height() Integer Возвращает высоту диапазона.
get Horizontal Alignment() String Возвращает горизонтальное выравнивание текста (слева/по центру/справа) ячейки в верхнем левом углу диапазона.
get Horizontal Alignments() String[][] Возвращает горизонтальное выравнивание ячеек в заданном диапазоне.
get Last Column() Integer Возвращает позицию в последнем столбце.
get Last Row() Integer Возвращает позицию в конце строки.
get Merged Ranges() Range[] Возвращает массив объектов Range , представляющих собой объединенные ячейки, которые либо полностью находятся в текущем диапазоне, либо содержат хотя бы одну ячейку в текущем диапазоне.
get Next Data Cell(direction) Range Начиная с ячейки в первом столбце и строке диапазона, функция возвращает следующую ячейку в заданном направлении, которая является границей непрерывного диапазона ячеек с данными или ячейкой на краю электронной таблицы в этом направлении.
get Note() String Возвращает примечание, связанное с заданным диапазоном.
get Notes() String[][] Возвращает примечания, связанные с ячейками в заданном диапазоне.
get Num Columns() Integer Возвращает количество столбцов в этом диапазоне.
get Num Rows() Integer Возвращает количество строк в этом диапазоне.
get Number Format() String Получите числовое или датовое форматирование ячейки в верхнем левом углу заданного диапазона.
get Number Formats() String[][] Возвращает числовой или датовый формат ячеек в заданном диапазоне.
get Rich Text Value() Rich Text Value |null Возвращает значение форматированного текста для ячейки в верхнем левом углу диапазона или null , если значение ячейки не является текстом.
get Rich Text Values() Rich Text Value[][] Возвращает значения в формате Rich Text для ячеек в заданном диапазоне.
get Row() Integer Возвращает позицию строки для данного диапазона.
get Row Index() Integer Возвращает позицию строки для данного диапазона.
get Sheet() Sheet Возвращает лист, к которому принадлежит данный диапазон.
get Text Direction() Text Direction Возвращает направление текста для верхней левой ячейки диапазона.
get Text Directions() Text Direction[][] Возвращает текстовые указания для ячеек в заданном диапазоне.
get Text Rotation() Text Rotation Возвращает параметры поворота текста для верхней левой ячейки диапазона.
get Text Rotations() Text Rotation[][] Возвращает параметры поворота текста для ячеек в заданном диапазоне.
get Text Style() Text Style Возвращает стиль текста для ячейки в верхнем левом углу диапазона.
get Text Styles() Text Style[][] Возвращает стили текста для ячеек в заданном диапазоне.
get Value() Object Возвращает значение ячейки в верхнем левом углу диапазона.
get Values() Object[][] Возвращает прямоугольную сетку значений для данного диапазона.
get Vertical Alignment() String Возвращает вертикальное выравнивание (сверху/посередине/снизу) ячейки в верхнем левом углу диапазона.
get Vertical Alignments() String[][] Возвращает вертикальное выравнивание ячеек в заданном диапазоне.
get Width() Integer Возвращает ширину диапазона в столбцах.
get Wrap() Boolean Возвращает значение, указывающее, переносится ли текст в ячейке на следующую строку.
get Wrap Strategies() Wrap Strategy[][] Возвращает стратегии переноса текста для ячеек в заданном диапазоне.
get Wrap Strategy() Wrap Strategy Возвращает стратегию переноса текста для ячейки в верхнем левом углу диапазона.
get Wraps() Boolean[][] Возвращает значение, указывающее, переносится ли текст в ячейках.
insert Cells(shiftDimension) Range Вставляет пустые ячейки в этот диапазон.
insert Checkboxes() Range Вставляет флажки в каждую ячейку диапазона, задавая значение true для отмеченных ячеек и false для неотмеченных.
insert Checkboxes(checkedValue) Range Вставляет флажки в каждую ячейку диапазона, задавая пользовательское значение для отмеченного состояния и пустую строку для неотмеченного.
insert Checkboxes(checkedValue, uncheckedValue) Range Вставляет флажки в каждую ячейку диапазона, задавая пользовательские значения для состояний "отмечено" и "не отмечено".
is Blank() Boolean Возвращает true если диапазон полностью пуст.
is Checked() Boolean Возвращает значение, указывающее, имеют ли все ячейки в диапазоне состояние флажка «отмечено».
is End Column Bounded() Boolean Определяет, привязан ли конец диапазона к определенному столбцу.
is End Row Bounded() Boolean Определяет, привязан ли конец диапазона к конкретной строке.
is Part Of Merge() Boolean Возвращает true если ячейки в текущем диапазоне перекрывают какие-либо объединенные ячейки.
is Start Column Bounded() Boolean Определяет, привязано ли начало диапазона к определенному столбцу.
is Start Row Bounded() Boolean Определяет, привязано ли начало диапазона к конкретной строке.
merge() Range Объединяет ячейки в заданном диапазоне в один блок.
merge Across() Range Объедините ячейки в диапазоне по столбцам этого диапазона.
merge Vertically() Range Объединяет ячейки в заданном диапазоне.
move To(target) void Скопируйте и вставьте (как формат, так и значения) из этого диапазона в целевой диапазон.
offset(rowOffset, columnOffset) Range Возвращает новый диапазон, смещенный относительно текущего диапазона на заданное количество строк и столбцов (которое может быть отрицательным).
offset(rowOffset, columnOffset, numRows) Range Возвращает новый диапазон, относительный к текущему диапазону, верхняя левая точка которого смещена относительно текущего диапазона на заданное количество строк и столбцов, а высота ячеек задана.
offset(rowOffset, columnOffset, numRows, numColumns) Range Возвращает новый диапазон, относительный к текущему диапазону, верхняя левая точка которого смещена относительно текущего диапазона на заданное количество строк и столбцов, а высота и ширина ячеек заданы.
protect() Protection Создает объект, который может защитить диапазон от редактирования, за исключением пользователей, имеющих соответствующие разрешения.
randomize() Range В случайном порядке меняет порядок строк в заданном диапазоне.
remove Checkboxes() Range Удаляет все флажки из диапазона.
remove Duplicates() Range Удаляет строки в этом диапазоне, содержащие значения, дублирующие значения из любой предыдущей строки.
remove Duplicates(columnsToCompare) Range Удаляет строки в указанном диапазоне, содержащие значения в указанных столбцах, которые являются дубликатами значений из любой предыдущей строки.
set Background(color) Range Задает цвет фона всех ячеек в диапазоне в формате CSS (например '#ffffff' или 'white' ).
set Background Object(color) Range Задает цвет фона для всех ячеек в диапазоне.
set Background Objects(color) Range Задает прямоугольную сетку фоновых цветов (размеры должны соответствовать указанному диапазону).
set Background RGB(red, green, blue) Range Устанавливает заданный цвет фона, используя значения RGB (целые числа от 0 до 255 включительно).
set Backgrounds(color) Range Задает прямоугольную сетку фоновых цветов (размеры должны соответствовать указанному диапазону).
set Border(top, left, bottom, right, vertical, horizontal) Range Устанавливает свойство границы.
set Border(top, left, bottom, right, vertical, horizontal, color, style) Range Задает свойства границы, включая цвет и/или стиль.
set Data Validation(rule) Range Устанавливает одно правило проверки данных для всех ячеек в заданном диапазоне.
set Data Validations(rules) Range Задает правила проверки данных для всех ячеек в заданном диапазоне.
set Font Color(color) Range Задает цвет шрифта в CSS-нотациях (например '#ffffff' или 'white' ).
set Font Color Object(color) Range Задает цвет шрифта для заданного диапазона.
set Font Color Objects(colors) Range Задает прямоугольную сетку цветов шрифта (размеры должны соответствовать указанному диапазону).
set Font Colors(colors) Range Задает прямоугольную сетку цветов шрифта (размеры должны соответствовать указанному диапазону).
set Font Families(fontFamilies) Range Задает прямоугольную сетку семейств шрифтов (размеры должны соответствовать указанному диапазону).
set Font Family(fontFamily) Range Задает семейство шрифтов, например, "Arial" или "Helvetica".
set Font Line(fontLine) Range Задает стиль шрифта для заданного диапазона строк ( 'underline' , 'line-through' или 'none' ).
set Font Lines(fontLines) Range Задает прямоугольную сетку стилей линий (должны соответствовать размерам указанного диапазона).
set Font Size(size) Range Задает размер шрифта, при этом размер указывается в пунктах.
set Font Sizes(sizes) Range Задает прямоугольную сетку размеров шрифта (размеры шрифта должны соответствовать указанному диапазону).
set Font Style(fontStyle) Range Задайте стиль шрифта для заданного диапазона ( 'italic' или 'normal' ).
set Font Styles(fontStyles) Range Задает прямоугольную сетку стилей шрифтов (размеры должны соответствовать указанному диапазону).
set Font Weight(fontWeight) Range Задайте толщину шрифта в заданном диапазоне (обычный/жирный).
set Font Weights(fontWeights) Range Задает прямоугольную сетку значений толщины шрифта (должны соответствовать размерам в указанном диапазоне).
set Formula(formula) Range Обновляет формулу для этого диапазона.
set Formula R1C1(formula) Range Обновляет формулу для этого диапазона.
set Formulas(formulas) Range Задает прямоугольную сетку формул (размеры должны соответствовать заданному диапазону).
set Formulas R1C1(formulas) Range Задает прямоугольную сетку формул (размеры должны соответствовать заданному диапазону).
set Horizontal Alignment(alignment) Range Установите горизонтальное (слева направо) выравнивание для заданного диапазона (слева/по центру/справа).
set Horizontal Alignments(alignments) Range Задает прямоугольную сетку горизонтальных линий выравнивания.
set Note(note) Range Устанавливает значение примечания равным заданному.
set Notes(notes) Range Задает прямоугольную сетку нот (размеры должны соответствовать указанному диапазону).
set Number Format(numberFormat) Range Задает формат числа или даты в соответствии с заданной строкой форматирования.
set Number Formats(numberFormats) Range Задает прямоугольную сетку числовых или датированных форматов (размеры должны соответствовать указанному диапазону).
set Rich Text Value(value) Range Задает значение форматированного текста для ячеек в заданном диапазоне.
set Rich Text Values(values) Range Задает прямоугольную сетку значений форматированного текста.
set Show Hyperlink(showHyperlink) Range Определяет, должны ли в диапазоне отображаться гиперссылки.
set Text Direction(direction) Range Задает направление текста для ячеек в заданном диапазоне.
set Text Directions(directions) Range Задает прямоугольную сетку текстовых указаний.
set Text Rotation(degrees) Range Задает параметры поворота текста для ячеек в заданном диапазоне.
set Text Rotation(rotation) Range Задает параметры поворота текста для ячеек в заданном диапазоне.
set Text Rotations(rotations) Range Задает прямоугольную сетку поворотов текста.
set Text Style(style) Range Задает стиль текста для ячеек в заданном диапазоне.
set Text Styles(styles) Range Задает прямоугольную сетку стилей текста.
set Value(value) Range Задает значение диапазона.
set Values(values) Range Задает прямоугольную сетку значений (должна соответствовать размерам этого диапазона).
set Vertical Alignment(alignment) Range Задайте вертикальное выравнивание (сверху вниз) для заданного диапазона (сверху/посередине/снизу).
set Vertical Alignments(alignments) Range Задает прямоугольную сетку вертикальных линий (должна соответствовать размерам этого диапазона).
set Vertical Text(isVertical) Range Определяет, следует ли располагать текст в ячейках диапазона друг над другом.
set Wrap(isWrapEnabled) Range Установите перенос строки в ячейках заданного диапазона.
set Wrap Strategies(strategies) Range Задает прямоугольную сетку стратегий переноса.
set Wrap Strategy(strategy) Range Задает стратегию переноса текста для ячеек в заданном диапазоне.
set Wraps(isWrapEnabled) Range Задает прямоугольную сетку правил переноса слов (размеры сетки должны соответствовать заданному диапазону).
shift Column Group Depth(delta) Range Изменяет глубину группировки столбцов диапазона на указанную величину.
shift Row Group Depth(delta) Range Изменяет глубину группировки строк диапазона на указанную величину.
sort(sortSpecObj) Range Сортирует ячейки в заданном диапазоне по столбцу и в указанном порядке.
split Text To Columns() void Разделяет столбец текста на несколько столбцов на основе автоматически определенного разделителя.
split Text To Columns(delimiter) void Разделяет столбец текста на несколько столбцов, используя указанную строку в качестве пользовательского разделителя.
split Text To Columns(delimiter) void Разделяет столбец текста на несколько столбцов на основе указанного разделителя.
trim Whitespace() Range Удаляет пробелы (например, пробелы, табуляции или переносы строк) из каждой ячейки в этом диапазоне.
uncheck() Range Изменяет состояние флажков в диапазоне на «не отмечено».

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

activate()

Устанавливает указанный диапазон в качестве active range , при этом верхняя левая ячейка в диапазоне является current cell .

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getRange('A1:D10');
range.activate();

const selection = sheet.getSelection();
// Current cell: A1
const currentCell = selection.getCurrentCell();
// Active Range: A1:D10
const activeRange = selection.getActiveRange();

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

Range — Этот диапазон предназначен для последовательного соединения.


activate As Current Cell()

Устанавливает указанную ячейку в качестве current cell .

Если указанная ячейка присутствует в существующем диапазоне, то этот диапазон становится активным, а указанная ячейка — текущей.

Если указанная ячейка отсутствует в каком-либо существующем диапазоне, то существующее выделение удаляется, и ячейка становится текущей ячейкой и активным диапазоном.

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

// Gets the first sheet of the spreadsheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];

// Gets the cell B5 and sets it as the active cell.
const range = sheet.getRange('B5');
const currentCell = range.activateAsCurrentCell();

// Logs the activated cell.
console.log(currentCell.getA1Notation());

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

add Developer Metadata(key)

Добавляет метаданные разработчика с указанным ключом в диапазон.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on the sheet.
const range = sheet.getRange('2:2');

// Adds the key 'NAME' to the developer metadata for row 2.
range.addDeveloperMetadata('NAME');

// Gets the metadata and logs it to the console.
const developerMetaData = range.getDeveloperMetadata()[0];
console.log(developerMetaData.getKey());

Параметры

Имя Тип Описание
key String Ключ к новым метаданным для разработчиков.

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

add Developer Metadata(key, visibility)

Добавляет метаданные разработчика с указанным ключом и уровнем видимости в заданный диапазон.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on Sheet1.
const range = sheet.getRange('2:2');

// Adds the key 'NAME' and sets the developer metadata visibility to 'DOCUMENT'
// for row 2 on Sheet1.
range.addDeveloperMetadata(
    'NAME',
    SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT,
);

// Gets the updated metadata info and logs it to the console.
const developerMetaData = range.getDeveloperMetadata()[0];
console.log(developerMetaData.getKey());
console.log(developerMetaData.getVisibility().toString());

Параметры

Имя Тип Описание
key String Ключ к новым метаданным для разработчиков.
visibility Developer Metadata Visibility Видимость новых метаданных разработчика.

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

add Developer Metadata(key, value)

Добавляет метаданные разработчика с указанным ключом и значением в заданный диапазон.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 of Sheet1.
const range = sheet.getRange('2:2');

// Adds the key 'NAME' and sets the value to 'GOOGLE' for the metadata of row 2.
range.addDeveloperMetadata('NAME', 'GOOGLE');

// Gets the metadata and logs it to the console.
const developerMetaData = range.getDeveloperMetadata()[0];
console.log(developerMetaData.getKey());
console.log(developerMetaData.getValue());

Параметры

Имя Тип Описание
key String Ключ к новым метаданным для разработчиков.
value String Значение для новых метаданных разработчика.

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

add Developer Metadata(key, value, visibility)

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on the sheet.
const range = sheet.getRange('2:2');

// Adds the key 'NAME', sets the value to 'GOOGLE', and sets the visibility
// to PROJECT for row 2 on the sheet.
range.addDeveloperMetadata(
    'NAME',
    'GOOGLE',
    SpreadsheetApp.DeveloperMetadataVisibility.PROJECT,
);

// Gets the updated metadata info and logs it to the console.
const developerMetaData = range.getDeveloperMetadata()[0];
console.log(developerMetaData.getKey());
console.log(developerMetaData.getValue());
console.log(developerMetaData.getVisibility().toString());

Параметры

Имя Тип Описание
key String Ключ к новым метаданным для разработчиков.
value String Значение для новых метаданных разработчика.
visibility Developer Metadata Visibility Видимость новых метаданных разработчика.

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

apply Column Banding()

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on the sheet.
const range = sheet.getRange('2:2');

// Applies column banding to row 2.
const colBanding = range.applyColumnBanding();

// Gets the first banding on the sheet and logs the color of the header column.
console.log(
    sheet.getBandings()[0]
        .getHeaderColumnColorObject()
        .asRgbColor()
        .asHexString(),
);

// Gets the first banding on the sheet and logs the color of the second column.
console.log(
    sheet.getBandings()[0]
        .getSecondColumnColorObject()
        .asRgbColor()
        .asHexString(),
);

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

Banding — новый метод кольцевания.

Авторизация

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

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

apply Column Banding(bandingTheme)

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on the sheet.
const range = sheet.getRange('2:2');

// Applies the INDIGO color banding theme to the columns in row 2.
const colBanding = range.applyColumnBanding(SpreadsheetApp.BandingTheme.INDIGO);

// Gets the first banding on the sheet and logs the color of the second column.
console.log(
    sheet.getBandings()[0]
        .getSecondColumnColorObject()
        .asRgbColor()
        .asHexString(),
);

Параметры

Имя Тип Описание
banding Theme Banding Theme Цветовая гамма для оформления колонн в этой серии.

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

Banding — новый метод кольцевания.

Авторизация

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

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

apply Column Banding(bandingTheme, showHeader, showFooter)

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets rows 12-22 on the sheet.
const range = sheet.getRange('12:22');

// Applies the BLUE color banding theme to rows 12-22.
// Sets the header visibility to false and the footer visibility to true.
const colBanding = range.applyColumnBanding(
    SpreadsheetApp.BandingTheme.BLUE,
    false,
    true,
);

// Gets the banding color and logs it to the console.
console.log(
    sheet.getBandings()[0]
        .getSecondColumnColorObject()
        .asRgbColor()
        .asHexString(),
);

// Gets the header color object and logs it to the console. Returns null because
// the header visibility is set to false.
console.log(sheet.getBandings()[0].getHeaderColumnColorObject());

// Gets the footer color and logs it to the console.
console.log(
    sheet.getBandings()[0]
        .getFooterColumnColorObject()
        .asRgbColor()
        .asHexString(),
);

Параметры

Имя Тип Описание
banding Theme Banding Theme Цветовая гамма для оформления колонн в этой серии.
show Header Boolean Если true , то цвет заголовка темы с полосами применяется к первому столбцу.
show Footer Boolean Если true , цвет нижнего колонтитула, заданный в теме оформления, применяется к последнему столбцу.

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

Banding — новый метод кольцевания.

Авторизация

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

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

apply Row Banding()

Применяет к диапазону стандартную тему оформления строк. По умолчанию оформление имеет цвет заголовка и не имеет цвета нижнего колонтитула.

// Opens the spreadsheet by its URL. If you created your script from within a
// Google Sheets spreadsheet, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets rows 1-30 on Sheet1.
const range = sheet.getRange('1:30');

// Applies row banding to rows 1-30.
range.applyRowBanding();

// Gets the hex color of the second banded row.
const secondRowColor =
    range.getBandings()[0].getSecondRowColorObject().asRgbColor().asHexString();

// Logs the hex color to console.
console.log(secondRowColor);

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

Banding — Склеивание полос.

Авторизация

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

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

apply Row Banding(bandingTheme)

Применяет указанную тему оформления строк к диапазону. По умолчанию оформление имеет цвет заголовка и не имеет цвета нижнего колонтитула.

// Opens the spreadsheet by its URL. If you created your script from within a
// Google Sheets spreadsheet, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets rows 1-30 on Sheet1.
const range = sheet.getRange('1:30');

// Applies the INDIGO row banding theme to rows 1-30.
range.applyRowBanding(SpreadsheetApp.BandingTheme.INDIGO);

// Gets the hex color of the second banded row.
const secondRowColor =
    range.getBandings()[0].getSecondRowColorObject().asRgbColor().asHexString();

// Logs the hex color to console.
console.log(secondRowColor);

Параметры

Имя Тип Описание
banding Theme Banding Theme Цветовая гамма, которую следует применить к строкам в диапазоне.

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

Banding — новый метод кольцевания.

Авторизация

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

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

apply Row Banding(bandingTheme, showHeader, showFooter)

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

// Opens the spreadsheet by its URL. If you created your script from within a
// Google Sheets spreadsheet, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets rows 1-30 on Sheet1.
const range = sheet.getRange('1:30');

// Applies the INDIGO row banding to rows 1-30 and
// specifies to hide the header and show the footer.
range.applyRowBanding(SpreadsheetApp.BandingTheme.INDIGO, false, true);

Параметры

Имя Тип Описание
banding Theme Banding Theme Цветовая гамма, которую следует применить к строкам в диапазоне.
show Header Boolean Если true , то цвет заголовка темы с полосами применяется к первой строке.
show Footer Boolean Если true , то цвет нижнего колонтитула, заданный в теме оформления, применяется к последней строке.

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

Banding — новый метод кольцевания.

Авторизация

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

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

auto Fill(destination, series)

Заполняет destination Range данными на основе данных в этом диапазоне. Новые значения также определяются указанным типом series . Целевой диапазон должен содержать этот диапазон и расширять его только в одном направлении. Например, следующий код заполняет ячейки A1:A20 рядом возрастающих чисел на основе текущих значений в A1:A4 :

const sheet = SpreadsheetApp.getActiveSheet();

// Has values [1, 2, 3, 4].
const sourceRange = sheet.getRange('A1:A4');
// The range to fill with values.
const destination = sheet.getRange('A1:A20');

// Inserts new values in A5:A20, continuing the pattern expressed in A1:A4
sourceRange.autoFill(destination, SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);

Параметры

Имя Тип Описание
destination Range Диапазон, который будет автоматически заполняться значениями. Целевой диапазон должен содержать этот диапазон и расширяться только в одном направлении (вверх, вниз, влево или вправо).
series Auto Fill Series Тип автозаполнения, который следует использовать для вычисления новых значений. Эффект от использования этого типа автозаполнения зависит от типа и объема исходных данных.

Авторизация

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

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

auto Fill To Neighbor(series)

Вычисляет диапазон для заполнения новыми данными на основе соседних ячеек и автоматически заполняет этот диапазон новыми значениями на основе содержащихся в нем данных. Эти новые значения также определяются указанным типом series .

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

Например, если A1:A20 заполнена рядом возрастающих чисел, и этот метод вызывается для диапазона B1:B4 , содержащего ряд дат, новые значения вставляются только в B5:B20 . Таким образом, эти новые значения «прикрепляются» к ячейкам, содержащим значения из столбца A.

const sheet = SpreadsheetApp.getActiveSheet();

// A1:A20 has values [1, 2, 3, ... 20].
// B1:B4 has values [1/1/2017, 1/2/2017, ...]
const sourceRange = sheet.getRange('B1:B4');

// Results in B5:B20 having values [1/5/2017, ... 1/20/2017]
sourceRange.autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);

Параметры

Имя Тип Описание
series Auto Fill Series Тип автозаполнения, который следует использовать для вычисления новых значений. Эффект от использования этого типа автозаполнения зависит от типа и объема исходных данных.

Авторизация

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

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

break Apart()

Разделите все ячейки в диапазоне, содержащие несколько столбцов, на отдельные ячейки.

Вызов этой функции для диапазона эквивалентен выбору диапазона и нажатию кнопки Формат > Объединить ячейки > Разъединить .

// Opens the spreadsheet by its URL. If you created your script from within a
// Google Sheets spreadsheet, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:C6 on Sheet1.
const range = sheet.getRange('A1:C6');

// Unmerges the range A1:C6 into individual cells.
range.breakApart();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

can Edit()

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

// Opens the spreadsheet by its URL. If you created your script from within a
// Google Sheets spreadsheet, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:C6 on Sheet1.
const range = sheet.getRange('A1:C6');

// Logs whether the user has permission to edit every cell in the range.
console.log(range.canEdit());

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

Booleantrue если у пользователя есть разрешение на редактирование каждой ячейки в диапазоне; false в противном случае.

Авторизация

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

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

check()

Изменяет состояние флажков в диапазоне на «отмечено». Игнорирует ячейки в диапазоне, которые в данный момент не содержат ни отмеченного, ни неотмеченного значения.

// Changes the state of cells which currently contain either the checked or
// unchecked value configured in the range A1:B10 to 'checked'.
const range = SpreadsheetApp.getActive().getRange('A1:B10');
range.check();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear()

Очищает диапазон содержимого и форматов.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.clear();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear(options)

Очищает диапазон содержимого, формата, правил проверки данных и/или комментариев в соответствии с заданными расширенными параметрами. По умолчанию очищаются все данные.

// The code below clears range C2:G7 in the active sheet, but preserves the
// format, data validation rules, and comments.
SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 5).clear({
  contentsOnly: true
});

Параметры

Имя Тип Описание
options Object Объект JavaScript, определяющий дополнительные параметры, перечисленные ниже.

Расширенные параметры

Имя Тип Описание
comments Only Boolean Очистить ли только комментарии.
contents Only Boolean Следует ли очищать только содержимое.
format Only Boolean Следует ли очищать только формат; обратите внимание, что очистка формата также очищает правила проверки данных.
validations Only Boolean Следует ли очищать только правила проверки данных.
skip Filtered Rows Boolean Следует ли избегать очистки отфильтрованных строк.

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear Content()

Очищает содержимое диапазона, сохраняя форматирование.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.clearContent();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear Data Validations()

Сбрасывает правила проверки данных для указанного диапазона.

// Clear the data validation rules for cells A1:B5.
const range = SpreadsheetApp.getActive().getRange('A1:B5');
range.clearDataValidations();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear Format()

Очищает форматирование для этого диапазона.

Это сбрасывает форматирование текста для ячейки или ячеек в диапазоне, но не изменяет правила форматирования чисел.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.clearFormat();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

clear Note()

Удаляет примечание в указанной ячейке или ячейках.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.clearNote();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

collapse Groups()

Объединяет все группы, которые полностью находятся в заданном диапазоне. Если ни одна группа не находится полностью в заданном диапазоне, объединяется самая глубокая расширенная группа, которая частично находится в этом диапазоне.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getActiveRange();

// All row and column groups within the range are collapsed.
range.collapseGroups();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

copy Format To Range(gridId, column, columnEnd, row, rowEnd)

Скопируйте форматирование диапазона в указанное место. Если целевой диапазон больше или меньше исходного, то исходный диапазон будет повторен или усечен соответственно. Обратите внимание, что этот метод копирует только форматирование.

Подробное описание параметра gridId см. в get Grid Id() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const source = ss.getSheets()[0];

const range = source.getRange('B2:D4');

// This copies the formatting in B2:D4 in the source sheet to
// D4:F6 in the sheet with gridId 1555299895. Note that you can get the gridId
// of a sheet by calling sheet.getSheetId() or range.getGridId().
range.copyFormatToRange(1555299895, 4, 6, 4, 6);

Параметры

Имя Тип Описание
grid Id Integer Уникальный идентификатор листа в электронной таблице, независимо от его положения.
column Integer Первый столбец целевого диапазона.
column End Integer Последний столбец целевого диапазона.
row Integer Начальная строка целевого диапазона.
row End Integer Последняя строка целевого диапазона.

Авторизация

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

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

См. также


copy Format To Range(sheet, column, columnEnd, row, rowEnd)

Скопируйте форматирование диапазона в указанное место. Если целевой диапазон больше или меньше исходного, то исходный диапазон будет повторен или усечен соответственно. Обратите внимание, что этот метод копирует только форматирование.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const source = ss.getSheets()[0];
const destination = ss.getSheets()[1];

const range = source.getRange('B2:D4');

// This copies the formatting in B2:D4 in the source sheet to
// D4:F6 in the second sheet
range.copyFormatToRange(destination, 4, 6, 4, 6);

Параметры

Имя Тип Описание
sheet Sheet Целевой лист.
column Integer Первый столбец целевого диапазона.
column End Integer Последний столбец целевого диапазона.
row Integer Начальная строка целевого диапазона.
row End Integer Последняя строка целевого диапазона.

Авторизация

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

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

copy To(destination)

Копирует данные из диапазона ячеек в другой диапазон ячеек. Копируются как значения, так и форматирование.

// The code below copies the first 5 columns over to the 6th column.
const sheet = SpreadsheetApp.getActiveSheet();
const rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));

Параметры

Имя Тип Описание
destination Range Диапазон ячеек, в который нужно скопировать данные; важна только позиция в верхнем левом углу ячейки.

Авторизация

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

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

copy To(destination, copyPasteType, transposed)

Копирует данные из диапазона ячеек в другой диапазон ячеек.

// The code below copies only the values of the first 5 columns over to the 6th
// column.
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A:E').copyTo(
    sheet.getRange('F1'),
    SpreadsheetApp.CopyPasteType.PASTE_VALUES,
    false,
);

Параметры

Имя Тип Описание
destination Range Диапазон ячеек, в который нужно скопировать данные; важна только позиция в верхнем левом углу ячейки.
copy Paste Type Copy Paste Type Тип, определяющий способ вставки содержимого диапазона в целевое место.
transposed Boolean Следует ли вставлять диапазон в транспонированной ориентации.

Авторизация

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

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

copy To(destination, options)

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

// The code below copies only the values of the first 5 columns over to the 6th
// column.
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A:E').copyTo(sheet.getRange('F1'), {contentsOnly: true});

Параметры

Имя Тип Описание
destination Range Диапазон ячеек, в который нужно скопировать данные; важна только позиция в верхнем левом углу ячейки.
options Object Объект JavaScript, определяющий дополнительные параметры, перечисленные ниже.

Расширенные параметры

Имя Тип Описание
format Only Boolean указывает, что копироваться следует только в формате.
contents Only Boolean указывает, что копироваться следует только содержимое.

Авторизация

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

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

copy Values To Range(gridId, column, columnEnd, row, rowEnd)

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

Подробное описание параметра gridId см. в get Grid Id() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const source = ss.getSheets()[0];

const range = source.getRange('B2:D4');

// This copies the data in B2:D4 in the source sheet to
// D4:F6 in the sheet with gridId 0
range.copyValuesToRange(0, 4, 6, 4, 6);

Параметры

Имя Тип Описание
grid Id Integer Уникальный идентификатор листа в электронной таблице, независимо от его положения.
column Integer Первый столбец целевого диапазона.
column End Integer Последний столбец целевого диапазона.
row Integer Начальная строка целевого диапазона.
row End Integer Последняя строка целевого диапазона.

Авторизация

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

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

См. также


copy Values To Range(sheet, column, columnEnd, row, rowEnd)

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

const ss = SpreadsheetApp.getActiveSpreadsheet();
const source = ss.getSheets()[0];
const destination = ss.getSheets()[1];

const range = source.getRange('B2:D4');

// This copies the data in B2:D4 in the source sheet to
// D4:F6 in the second sheet
range.copyValuesToRange(destination, 4, 6, 4, 6);

Параметры

Имя Тип Описание
sheet Sheet Целевой лист.
column Integer Первый столбец целевого диапазона.
column End Integer Последний столбец целевого диапазона.
row Integer Начальная строка целевого диапазона.
row End Integer Последняя строка целевого диапазона.

Авторизация

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

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

create Data Source Pivot Table(dataSource)

Создает пустую сводную таблицу на основе исходных данных, привязанную к первой ячейке в этом диапазоне.

В этом примере показано, как создать и настроить новую сводную таблицу источника данных.

const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const anchorCell = spreadsheet.getSheets()[0].getRange('A1');
const dataSource = spreadsheet.getDataSources()[0];

const pivotTable = anchorCell.createDataSourcePivotTable(dataSource);
pivotTable.addRowGroup('dataColumnA');
pivotTable.addColumnGroup('dataColumnB');
pivotTable.addPivotValue(
    'dataColumnC',
    SpreadsheetApp.PivotTableSummarizeFunction.SUM,
);
pivotTable.addFilter(
    'dataColumnA',
    SpreadsheetApp.newFilterCriteria().whenTextStartsWith('A').build(),
);

Параметры

Имя Тип Описание
data Source Data Source Источник данных, на основе которого будет создана сводная таблица.

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

Data Source Pivot Table — новая сводная таблица источника данных.

Авторизация

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

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

create Data Source Table(dataSource)

Создает пустую таблицу источника данных на основе исходных данных, привязанную к первой ячейке в этом диапазоне.

В этом примере показано, как создать и настроить новую таблицу-источник данных.

const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const anchorCell = spreadsheet.getSheets()[0].getRange('A1');
const dataSource = spreadsheet.getDataSources()[0];

const dataSourceTable =
    anchorCell.createDataSourceTable(dataSource)
        .addColumns('dataColumnA', 'dataColumnB', 'dataColumnC')
        .addSortSpec('dataColumnA', true)    // ascending=true
        .addSortSpec('dataColumnB', false);  // ascending=false

Параметры

Имя Тип Описание
data Source Data Source Источник данных, на основе которого будет создана сводная таблица.

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

Data Source Table — Вновь созданная таблица источников данных.

Авторизация

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

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

create Developer Metadata Finder()

Возвращает объект DeveloperMetadataFinderApi для поиска метаданных разработчика в пределах указанного диапазона. Метаданные находятся в пределах диапазона только в том случае, если они полностью содержатся в этом диапазоне. Например, метаданные, связанные со строкой '3:3', не находятся в пределах диапазона 'A1:D5', но находятся в пределах диапазона '1:5'.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:C6.
const range = sheet.getRange('A1:C6');

// Creates a developer metadata finder to search for metadata in the scope of
// this range.
const developerMetaDataFinder = range.createDeveloperMetadataFinder();

// Logs information about the developer metadata finder to the console.
const developerMetaData = developerMetaDataFinder.find()[0];
console.log(developerMetaData.getKey());
console.log(developerMetaData.getValue());
console.log(developerMetaData.getVisibility().toString());

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

Developer Metadata Finder — средство поиска метаданных в указанном диапазоне.


create Filter()

Создает фильтр и применяет его к указанному диапазону на листе. На одном листе нельзя создать более одного фильтра. Чтобы получить доступ к созданному фильтру и изменить его, используйте get Filter() или Sheet.getFilter() .

const ss = SpreadsheetApp.getActiveSheet();
const range = ss.getRange('A1:C20');

// Creates a new filter and applies it to the range A1:C20 on the active sheet.
function createFilter() {
  range.createFilter();
}
// Gets the filter and applies criteria that only shows cells that aren't empty.
function getFilterAddCriteria() {
  const filter = range.getFilter();
  const criteria =
      SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
  filter.setColumnFilterCriteria(2, criteria);
}
Этот метод используется для создания фильтров для таблиц Grid sheets), которые являются типом таблиц по умолчанию. Таблицы — это таблицы, не связанные с базой данных. Для создания других типов фильтров см. следующие инструкции:

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

Filter — новый фильтр.

Авторизация

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

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

create Pivot Table(sourceData)

Создает пустую сводную таблицу на основе указанных source Data привязанных к первой ячейке в этом диапазоне.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets cell A1 as a range in order to place the pivot table.
const range = sheet.getRange('A1');

// Gets the range of the source data for the pivot table.
const dataRange = sheet.getRange('E12:G20');

// Creates an empty pivot table from the specified source data.
const pivotTable = range.createPivotTable(dataRange);

// Logs the values from the pivot table's source data to the console.
console.log(pivotTable.getSourceDataRange().getValues());

Параметры

Имя Тип Описание
source Data Range Данные, на основе которых будет создана сводная таблица.

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

Pivot Table — недавно созданная Pivot Table .

Авторизация

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

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

create Text Finder(findText)

Создает средство поиска текста для заданного диапазона, которое может находить и заменять текст в этом диапазоне.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getActiveRange();

// Creates  a text finder for the range.
const textFinder = range.createTextFinder('dog');

// Returns the first occurrence of 'dog'.
const firstOccurrence = textFinder.findNext();

// Replaces the last found occurrence of 'dog' with 'cat' and returns the number
// of occurrences replaced.
const numOccurrencesReplaced = textFinder.replaceWith('cat');

Параметры

Имя Тип Описание
find Text String Текст для поиска.

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

Text FinderText Finder для стрельбища


delete Cells(shiftDimension)

Удаляет указанный диапазон ячеек. Существующие данные на листе вдоль заданного измерения сдвигаются в сторону удаляемого диапазона.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.deleteCells(SpreadsheetApp.Dimension.COLUMNS);

Параметры

Имя Тип Описание
shift Dimension Dimension Измерение, вдоль которого следует сдвигать существующие данные.

Авторизация

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

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

expand Groups()

Разворачивает свернутые группы, диапазон или переключатель управления которых пересекаются с этим диапазоном. Местоположение переключателя управления — это индекс, по которому отображается переключатель, непосредственно перед или после группы в зависимости от настроек. Если в одном и том же месте находится более одной группы, разворачивается самая узкая группа.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getActiveRange();

// All row and column groups within the range are expanded.
range.expandGroups();

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

Range — Этот диапазон предназначен для последовательного соединения.

Авторизация

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

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

getA1Notation()

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

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange(1, 1, 2, 5);

// Logs "A1:E2"
Logger.log(range.getA1Notation());

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

String — строковое описание диапазона в формате A1.

Авторизация

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

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

get Background()

Возвращает цвет фона ячейки в верхнем левом углу диапазона (например, '#ffffff' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B5');
Logger.log(cell.getBackground());

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

String — цветовой код фона.

Авторизация

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

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

get Background Object()

Возвращает цвет фона ячейки в верхнем левом углу диапазона.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B5');
Logger.log(cell.getBackgroundObject().asRgbColor().asHexString());

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

Color — цвет фона ячейки в верхнем левом углу диапазона.

Авторизация

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

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

get Background Objects()

Возвращает цвет фона ячеек в заданном диапазоне.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5:C6');
const bgColors = range.getBackgroundObjects();
for (const i in bgColors) {
  for (const j in bgColors[i]) {
    Logger.log(bgColors[i][j].asRgbColor().asHexString());
  }
}

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

Color[][] — Двумерный массив фоновых цветов.

Авторизация

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

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

get Backgrounds()

Возвращает цвет фона ячеек в заданном диапазоне (например, '#ffffff' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5:C6');
const bgColors = range.getBackgrounds();
for (const i in bgColors) {
  for (const j in bgColors[i]) {
    Logger.log(bgColors[i][j]);
  }
}

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

String[][] — Двумерный массив цветовых кодов фонов.

Авторизация

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

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

get Bandings()

Возвращает все полосы, примененные к любым ячейкам в этом диапазоне.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Sets a range.
const range = sheet.getRange('A1:K50');

// Gets the banding info for the range.
const bandings = range.getBandings();

// Logs the second row color for each banding to the console.
for (const banding of bandings) {
  console.log(banding.getSecondRowColor());
}

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

Banding[] — Все полосы, которые применяются к любым клеткам в этом диапазоне.

Авторизация

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

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

get Cell(row, column)

Возвращает заданную ячейку в указанном диапазоне.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D4');

// The row and column here are relative to the range
// getCell(1,1) in this code returns the cell at B2
const cell = range.getCell(1, 1);
Logger.log(cell.getValue());

Параметры

Имя Тип Описание
row Integer Строка ячейки относительно заданного диапазона.
column Integer Столбец ячейки относительно заданного диапазона.

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

Range — диапазон, содержащий одну ячейку по указанным координатам.

Авторизация

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

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

get Column()

Возвращает начальную позицию столбца для данного диапазона.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D4');
// Logs "2.0"
Logger.log(range.getColumn());

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

Integer — начальная позиция столбца диапазона в электронной таблице.

Авторизация

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

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

get Data Region()

Возвращает копию диапазона, расширенную по четырем основным Direction , чтобы охватить все смежные ячейки, содержащие данные. Если диапазон окружен пустыми ячейками, за исключением ячеек вдоль диагоналей, возвращается сам диапазон. Это аналогично выделению диапазона и нажатию Ctrl+A в редакторе.

// Assume the active spreadsheet is blank.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
sheet.getRange('C2').setValue(100);
sheet.getRange('B3').setValue(100);
sheet.getRange('D3').setValue(100);
sheet.getRange('C4').setValue(100);
// Logs "B2:D4"
Logger.log(sheet.getRange('C3').getDataRegion().getA1Notation());

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

Range — область данных или диапазон для всей электронной таблицы.

Авторизация

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

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

get Data Region(dimension)

Возвращает копию расширенного диапазона. Если указанное измерение равно Dimension.ROWS , возвращаются Direction.UP и Direction.DOWN , а если измерение равно Dimension.COLUMNS , возвращаются Direction.NEXT и Direction.PREVIOUS . Расширение диапазона основано на обнаружении данных, расположенных рядом с диапазоном и организованных как таблица. Расширенный диапазон охватывает все смежные ячейки с данными вдоль указанного измерения, включая границы таблицы. Если исходный диапазон окружен пустыми ячейками вдоль указанного измерения, возвращается сам диапазон. Этот метод аналогичен выделению диапазона и нажатию Ctrl+Space для столбцов или Shift+Space для строк в редакторе.

// Assume the active spreadsheet is blank.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
sheet.getRange('C2').setValue(100);
sheet.getRange('B3').setValue(100);
sheet.getRange('D3').setValue(100);
sheet.getRange('C4').setValue(100);
// Logs "C2:C4"
Logger.log(
    sheet.getRange('C3')
        .getDataRegion(SpreadsheetApp.Dimension.ROWS)
        .getA1Notation(),
);
// Logs "B3:D3"
Logger.log(
    sheet.getRange('C3')
        .getDataRegion(SpreadsheetApp.Dimension.COLUMNS)
        .getA1Notation(),
);

Параметры

Имя Тип Описание
dimension Dimension Размерность, вдоль которой следует расширять диапазон.

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

Range — область данных диапазона или диапазон, охватывающий каждый столбец или каждую строку, которые занимал исходный диапазон.

Авторизация

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

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

get Data Source Formula()

Возвращает Data Source Formula для первой ячейки в диапазоне или null , если ячейка не содержит формулу источника данных.

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1 on Sheet1.
const range = sheet.getRange('A1');

// Gets the data source formula from cell A1.
const dataSourceFormula = range.getDataSourceFormula();

// Gets the formula.
const formula = dataSourceFormula.getFormula();

// Logs the formula.
console.log(formula);

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

Data Source Formula |nullData Source Formula для ячейки.

Авторизация

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

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

get Data Source Formulas()

Возвращает Data Source Formula для ячеек в заданном диапазоне.

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:B5 on Sheet1.
const range = sheet.getRange('A1:B5');

// Gets an array of the data source formulas in the range A1:B5.
const dataSourceFormulas = range.getDataSourceFormulas();

// Logs the first formula in the array.
console.log(dataSourceFormulas[0].getFormula());

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

Data Source Formula[] — массив Data Source Formula .

Авторизация

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

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

get Data Source Pivot Tables()

Получает все сводные таблицы источников данных, пересекающиеся с заданным диапазоном.

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:G50 on Sheet1.
const range = sheet.getRange('A1:G50');

// Gets an array of the data source pivot tables in the range A1:G50.
const dataSourcePivotTables = range.getDataSourcePivotTables();

// Logs the last time that the first pivot table in the array was refreshed.
console.log(dataSourcePivotTables[0].getStatus().getLastRefreshedTime());

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

Data Source Pivot Table[] — Список сводных таблиц источников данных.

Авторизация

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

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

get Data Source Tables()

Получает все таблицы источников данных, пересекающиеся с заданным диапазоном.

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:G50 on Sheet1.
const range = sheet.getRange('A1:G50');

// Gets the first data source table in the range A1:G50.
const dataSourceTable = range.getDataSourceTables()[0];

// Logs the time of the last completed data execution on the data source table.
console.log(dataSourceTable.getStatus().getLastExecutionTime());

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

Data Source Table[] — Список таблиц источников данных.

Авторизация

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

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

get Data Source Url()

Возвращает URL-адрес данных в указанном диапазоне, который можно использовать для создания диаграмм и запросов.

Code.gs

function doGet() {
  const ss = SpreadsheetApp.openById(
      '1khO6hBWTNNyvyyxvob7aoZTI9ZvlqqASNeq0e29Tw2c',
  );
  const sheet = ss.getSheetByName('ContinentData');
  const range = sheet.getRange('A1:B8');

  const template = HtmlService.createTemplateFromFile('piechart');
  template.dataSourceUrl = range.getDataSourceUrl();
  return template.evaluate();
}

piechart.html

<!DOCTYPE html>
<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages': ['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(queryData);

      function queryData() {
        var query = new google.visualization.Query('<?= dataSourceUrl ?>');
        query.send(drawChart);
      }

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart(response) {
        if (response.isError()) {
          alert('Error: ' + response.getMessage() + ' ' + response.getDetailedMessage());
          return;
        }
        var data = response.getDataTable();

        // Set chart options.
        var options = {
          title: 'Population by Continent',
          width: 400,
          height: 300
        };

        // Instantiate and draw the chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <!-- Div that holds the pie chart. -->
    <div id="chart_div"></div>
  </body>
</html>

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

String — URL-адрес этого диапазона в качестве источника данных, который можно передавать другим API, например, для построения диаграмм.

Авторизация

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

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

get Data Table()

Возвращает данные из этого объекта в виде DataTable.

// Opens the spreadsheet file by its ID. If you created your script from a
// Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet().
// TODO(developer): Replace the ID with your own.
const ss = SpreadsheetApp.openById('abc123456');

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:B7 on Sheet1.
const range = sheet.getRange('A1:B7');

// Gets the range A1:B7 as a data table. The values in each column must be of
// the same type.
const datatable = range.getDataTable();

// Uses the Charts service to build a bar chart from the data table.
// This doesn't build an embedded chart. To do that, use
// sheet.newChart().addRange() instead.
const chart = Charts.newBarChart()
                  .setDataTable(datatable)
                  .setOption('title', 'Your Chart Title Here')
                  .build();

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

Data Table — данные в виде таблицы данных.


get Data Table(firstRowIsHeader)

Верните данные из этого диапазона в виде объекта DataTable.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('A1:B7');

// Calling this method with "true" sets the first line to be the title of the
// axes
const datatable = range.getDataTable(true);

// Note that this doesn't build an EmbeddedChart, so you can't just use
// Sheet#insertChart(). To do that, use sheet.newChart().addRange() instead.
const chart = Charts.newBarChart()
                  .setDataTable(datatable)
                  .setOption('title', 'Your Title Here')
                  .build();

Параметры

Имя Тип Описание
first Row Is Header Boolean Следует ли рассматривать первую строку как заголовок.

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

Data Table — данные в виде таблицы.

Авторизация

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

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

get Data Validation()

Возвращает правило проверки данных для ячейки в верхнем левом углу диапазона. Если проверка данных для ячейки не задана, этот метод возвращает null .

// Log information about the data validation rule for cell A1.
const cell = SpreadsheetApp.getActive().getRange('A1');
const rule = cell.getDataValidation();
if (rule != null) {
  const criteria = rule.getCriteriaType();
  const args = rule.getCriteriaValues();
  Logger.log('The data validation rule is %s %s', criteria, args);
} else {
  Logger.log('The cell does not have a data validation rule.');
}

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

Data Validation — правило проверки данных для ячейки в верхнем левом углу диапазона.

Авторизация

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

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

get Data Validations()

Возвращает правила проверки данных для всех ячеек в диапазоне. Если для данной ячейки не заданы правила проверки данных, этот метод возвращает null для позиции этой ячейки в массиве.

// Change existing data validation rules that require a date in 2013 to require
// a date in 2014.
const oldDates = [new Date('1/1/2013'), new Date('12/31/2013')];
const newDates = [new Date('1/1/2014'), new Date('12/31/2014')];
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
const rules = range.getDataValidations();

for (let i = 0; i < rules.length; i++) {
  for (let j = 0; j < rules[i].length; j++) {
    const rule = rules[i][j];

    if (rule != null) {
      const criteria = rule.getCriteriaType();
      const args = rule.getCriteriaValues();

      if (criteria === SpreadsheetApp.DataValidationCriteria.DATE_BETWEEN &&
          args[0].getTime() === oldDates[0].getTime() &&
          args[1].getTime() === oldDates[1].getTime()) {
        // Create a builder from the existing rule, then change the dates.
        rules[i][j] = rule.copy().withCriteria(criteria, newDates).build();
      }
    }
  }
}
range.setDataValidations(rules);

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

Data Validation[][] — Двумерный массив правил проверки данных, связанных с ячейками в диапазоне.

Авторизация

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

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

get Developer Metadata()

Получает метаданные разработчика, связанные с этим диапазоном.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets row 2 on Sheet1.
const range = sheet.getRange('2:2');

// Adds metadata to row 2.
range.addDeveloperMetadata('NAME', 'GOOGLE');

// Logs the metadata to console.
for (const metadata of range.getDeveloperMetadata()) {
  console.log(`${metadata.getKey()}: ${metadata.getValue()}`);
}

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

Developer Metadata[] — Метаданные разработчика, связанные с этим диапазоном.

Авторизация

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

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

get Display Value()

Возвращает отображаемое значение ячейки в верхнем левом углу диапазона. Значение представляет собой String . Отображаемое значение учитывает форматирование даты, времени и валюты, включая форматы, применяемые автоматически в соответствии с языковыми настройками электронной таблицы. Для пустых ячеек возвращается пустая строка.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets cell A30 and sets its value to 'Test code.'
const cell = sheet.getRange('A30');
cell.setValue('Test code');

// Gets the value and logs it to the console.
console.log(cell.getDisplayValue());

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

String — значение, отображаемое в этой ячейке.

Авторизация

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

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

get Display Values()

Возвращает прямоугольную сетку значений для данного диапазона.

Возвращает двумерный массив отображаемых значений, индексированных по строкам, а затем по столбцам. Значения представляют собой String объекты. Отображаемое значение учитывает форматирование даты, времени и валюты, включая форматы, применяемые автоматически настройками локали электронной таблицы. Пустые ячейки представлены пустой строкой в ​​массиве. Помните, что хотя индекс диапазона начинается с 1, 1 , массив JavaScript индексируется с [0][0] .

// The code below gets the displayed values for the range C2:G8
// in the active spreadsheet.  Note that this is a JavaScript array.
const values =
    SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getDisplayValues();
Logger.log(values[0][0]);

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

String[][] — Двумерный массив значений.

Авторизация

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

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

get Filter()

Возвращает фильтр на листе, к которому принадлежит данный диапазон, или null если на листе нет фильтра.

const ss = SpreadsheetApp.getActiveSheet();
const range = ss.getRange('A1:C20');
// Gets the existing filter on the sheet that the given range belongs to.
const filter = range.getFilter();

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

Filter |null — Фильтр.

Авторизация

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

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

get Font Color Object()

Возвращает цвет шрифта ячейки в верхнем левом углу диапазона.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontColorObject().asRgbColor().asHexString());

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

Color — цвет шрифта ячейки в верхнем левом углу диапазона.

Авторизация

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

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

get Font Color Objects()

Возвращает цвет шрифта ячеек в заданном диапазоне.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontColorObjects();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j].asRgbColor().asHexString());
  }
}

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

Color[][] — Двумерный массив цветов шрифта, связанных с ячейками в диапазоне.

Авторизация

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

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

get Font Families()

Возвращает семейства шрифтов ячеек в заданном диапазоне.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontFamilies();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — Двумерный массив семейств шрифтов, связанных с ячейками в диапазоне.

Авторизация

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

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

get Font Family()

Возвращает семейство шрифтов ячейки, расположенной в верхнем левом углу диапазона.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontFamily());

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

String — Семейство шрифтов ячейки.

Авторизация

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

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

get Font Line()

Gets the line style of the cell in the top-left corner of the range ( 'underline' , 'line-through' , or 'none' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontLine());

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

String — The font line.

Авторизация

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

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

get Font Lines()

Gets the line style of the cells in the range ( 'underline' , 'line-through' , or 'none' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontLines();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of font lines associated with cells in the range.

Авторизация

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

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

get Font Size()

Returns the font size in point size of the cell in the top-left corner of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontSize());

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

Integer — The font size in point size.

Авторизация

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

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

get Font Sizes()

Returns the font sizes of the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontSizes();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

Integer[][] — A two-dimensional array of font sizes of text associated with cells in the range.

Авторизация

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

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

get Font Style()

Returns the font style ( 'italic' or 'normal' ) of the cell in the top-left corner of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontStyle());

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

String — The font style of the text in the cell.

Авторизация

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

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

get Font Styles()

Returns the font styles of the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontStyles();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of font styles of text associated with cells in the range.

Авторизация

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

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

get Font Weight()

Returns the font weight (normal/bold) of the cell in the top-left corner of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getFontWeight());

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

String — The font weight of the text in the cell.

Авторизация

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

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

get Font Weights()

Returns the font weights of the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getFontWeights();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of font weights of text associated with cells in the range.

Авторизация

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

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

get Formula()

Returns the formula (A1 notation) for the top-left cell of the range, or an empty string if the cell is empty or doesn't contain a formula.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// This assumes you have a function in B5 that sums up
// B2:B4
const range = sheet.getRange('B5');

// Logs the calculated value and the formula
Logger.log(
    'Calculated value: %s Formula: %s',
    range.getValue(),
    range.getFormula(),
);

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

String — The formula for the cell.

Авторизация

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

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

get Formula R1C1()

Returns the formula (R1C1 notation) for a given cell, or null if none.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5');
const formula = range.getFormulaR1C1();
Logger.log(formula);

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

String — The formula in R1C1 notation.

Авторизация

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

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

get Formulas()

Returns the formulas (A1 notation) for the cells in the range. Entries in the 2D array are empty strings for cells with no formula.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5:C6');
const formulas = range.getFormulas();
for (const i in formulas) {
  for (const j in formulas[i]) {
    Logger.log(formulas[i][j]);
  }
}

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

String[][] — A two-dimensional array of formulas in string format.

Авторизация

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

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

get Formulas R1C1()

Returns the formulas (R1C1 notation) for the cells in the range. Entries in the 2D array are null for cells with no formula.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5:C6');
const formulas = range.getFormulasR1C1();
for (const i in formulas) {
  for (const j in formulas[i]) {
    Logger.log(formulas[i][j]);
  }
}

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

String[][] — A two-dimensional array of formulas in R1C1 notation.

Авторизация

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

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

get Grid Id()

Returns the grid ID of the range's parent sheet. IDs are random non-negative int values.

// Log the grid ID of the first sheet (by tab position) in the spreadsheet.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getGridId());

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

Integer — The grid ID of the parent sheet.

Авторизация

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

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

get Height()

Returns the height of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D4');
// logs 3.0
Logger.log(range.getHeight());

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

Integer — The height of the range.

Авторизация

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

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

get Horizontal Alignment()

Returns the horizontal alignment of the text (left/center/right) of the cell in the top-left corner of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getHorizontalAlignment());

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

String — The horizontal alignment of the text in the cell.

Авторизация

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

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

get Horizontal Alignments()

Returns the horizontal alignments of the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getHorizontalAlignments();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of horizontal alignments of text associated with cells in the range.

Авторизация

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

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

get Last Column()

Returns the end column position.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D4');
// Logs "4.0"
Logger.log(range.getLastColumn());

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

Integer — The range's ending column position in the spreadsheet.

Авторизация

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

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

get Last Row()

Returns the end row position.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D4');
// Logs "4.0"
Logger.log(range.getLastRow());

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

Integer — The range's ending row position in the spreadsheet.

Авторизация

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

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

get Merged Ranges()

Returns an array of Range objects representing merged cells that either are fully within the current range, or contain at least one cell in the current range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:B3');

const mergedRanges = range.getMergedRanges();
for (let i = 0; i < mergedRanges.length; i++) {
  Logger.log(mergedRanges[i].getA1Notation());
  Logger.log(mergedRanges[i].getDisplayValue());
}

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

Range[] — An array of Range objects, representing merged cells overlapping the range.


get Next Data Cell(direction)

Starting at the cell in the first column and row of the range, returns the next cell in the given direction that is the edge of a contiguous range of cells with data in them or the cell at the edge of the spreadsheet in that direction. This is equivalent to typing Ctrl+[arrow key] in the editor.

// Assume the active spreadsheet is blank.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('C3:E5');
// Logs "C1"
Logger.log(range.getNextDataCell(SpreadsheetApp.Direction.UP).getA1Notation());

Параметры

Имя Тип Описание
direction Direction Направление, в котором следует найти следующую ячейку на краю области данных.

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

Range — The data region edge cell or the cell at the edge of the spreadsheet.

Авторизация

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

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

get Note()

Returns the note associated with the given range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getNote());

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

String — The note associated with the given cell.

Авторизация

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

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

get Notes()

Returns the notes associated with the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getNotes();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of notes associated with cells in the range.

Авторизация

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

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

get Num Columns()

Returns the number of columns in this range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D5');
Logger.log(range.getNumColumns());

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

Integer — The number of columns in this range.

Авторизация

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

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

get Num Rows()

Returns the number of rows in this range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D5');
Logger.log(range.getNumRows());

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

Integer — The number of rows in this range.

Авторизация

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

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

get Number Format()

Get the number or date formatting of the top-left cell of the given range. The returned format patterns are described in the Sheets API documentation .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('C4');
Logger.log(cell.getNumberFormat());

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

String — The number format of the top-left cell of the range.

Авторизация

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

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

get Number Formats()

Returns the number or date formats for the cells in the range. The returned format patterns are described in the Sheets API documentation .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B5:C6');
const formats = range.getNumberFormats();
for (const i in formats) {
  for (const j in formats[i]) {
    Logger.log(formats[i][j]);
  }
}

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

String[][] — A two-dimensional array of number formats.

Авторизация

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

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

get Rich Text Value()

Returns the Rich Text value for the top left cell of the range, or null if the cell value is not text.

// Gets the Rich Text value of cell D4.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('D4:F6');
const richText = range.getRichTextValue();
console.log(richText.getText());

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

Rich Text Value |null — The Rich Text value of the top left cell in the range, or null if the cell value is not text.

Авторизация

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

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

get Rich Text Values()

Returns the Rich Text values for the cells in the range.

// Gets the Rich Text values for all cells in range B5:C6
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B5:C6');
const values = range.getRichTextValues();

for (let i = 0; i < values.length; i++) {
  for (let j = 0; j < values[i].length; j++) {
    console.log(values[i][j].getText());
  }
}

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

Rich Text Value[][] — A two-dimensional array of Rich Text values.

Авторизация

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

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

get Row()

Returns the row position for this range. Identical to get Row Index() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2');
Logger.log(range.getRow());

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

Integer — The row position of the range.

Авторизация

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

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

get Row Index()

Returns the row position for this range. Identical to get Row() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2');
Logger.log(range.getRowIndex());

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

Integer — The row position of the range.

Авторизация

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

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

См. также


get Sheet()

Returns the sheet this range belongs to.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Gets the sheet that the range belongs to.
const rangeSheet = range.getSheet();

// Gets the sheet name and logs it to the console.
console.log(rangeSheet.getName());

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

Sheet — The sheet that this range belongs to.

Авторизация

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

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

get Text Direction()

Returns the text direction for the top left cell of the range. Returns null if the cell text direction is determined with automatic detection.

// Get the text direction of cell B1.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B1:D4');
Logger.log(range.getTextDirection());

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

Text Direction — The text direction of the top left cell in the range.

Авторизация

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

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

get Text Directions()

Returns the text directions for the cells in the range. Entries in the 2D array are null for cells using automatic detection.

// Get the text directions for all cells in range B5:C6
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B5:C6');
const directions = range.getTextDirections();

for (let i = 0; i < directions.length; i++) {
  for (let j = 0; j < directions[i].length; j++) {
    Logger.log(directions[i][j]);
  }
}

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

Text Direction[][] — A two-dimensional array of text directions.

Авторизация

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

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

get Text Rotation()

Returns the text rotation settings for the top left cell of the range.

// Log the text rotation settings for a cell.
const sheet = SpreadsheetApp.getActiveSheet();

const cell = sheet.getRange('A1');
Logger.log(cell.getTextRotation());

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

Text Rotation — The text rotation settings.

Авторизация

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

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

get Text Rotations()

Returns the text rotation settings for the cells in the range.

const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B2:D4');

const results = range.getTextRotations();

for (const i in results) {
  for (const j in results[i]) {
    const rotation = results[i][j];
    Logger.log('Cell [%s, %s] has text rotation: %v', i, j, rotation);
  }
}

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

Text Rotation[][] — A two-dimensional array of text rotations associated with cells in the range.

Авторизация

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

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

get Text Style()

Returns the text style for the top left cell of the range.

// Get the text style of cell D4.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('D4:F6');
const style = range.getTextStyle();
Logger.log(style);

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

Text Style — The text style of the top left cell in the range.

Авторизация

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

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

get Text Styles()

Returns the text styles for the cells in the range.

// Get the text styles for all cells in range B5:C6
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B5:C6');
const styles = range.getTextStyles();

for (let i = 0; i < styles.length; i++) {
  for (let j = 0; j < styles[i].length; j++) {
    Logger.log(styles[i][j]);
  }
}

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

Text Style[][] — A two-dimensional array of text styles.

Авторизация

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

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

get Value()

Returns the value of the top-left cell in the range. The value may be of type Number , Boolean , Date , or String depending on the value of the cell. Empty cells return an empty string.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Gets the value of the top-left cell in the range and logs it to the console.
console.log(range.getValue());

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

Object — The value in this cell.

Авторизация

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

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

get Values()

Returns the rectangular grid of values for this range.

Returns a two-dimensional array of values, indexed by row, then by column. The values may be of type Number , Boolean , Date , or String , depending on the value of the cell. Empty cells are represented by an empty string in the array. Remember that while a range index starts at 1, 1 , the JavaScript array is indexed from [0][0] .

// The code below gets the values for the range C2:G8
// in the active spreadsheet.  Note that this is a JavaScript array.
const values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getValues();
Logger.log(values[0][0]);
In web apps, a Date value isn't a legal parameter. get Values() fails to return data to a web app if the range contains a cell with a Date value. Instead, transform all the values retrieved from the sheet to a supported JavaScript primitive like a Number , Boolean , or String .

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

Object[][] — A two-dimensional array of values.

Авторизация

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

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

get Vertical Alignment()

Returns the vertical alignment (top/middle/bottom) of the cell in the top-left corner of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getVerticalAlignment());

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

String — The vertical alignment of the text in the cell.

Авторизация

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

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

get Vertical Alignments()

Returns the vertical alignments of the cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getVerticalAlignments();

for (const i in results) {
  for (const j in results[i]) {
    Logger.log(results[i][j]);
  }
}

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

String[][] — A two-dimensional array of vertical alignments of text associated with cells in the range.

Авторизация

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

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

get Width()

Returns the width of the range in columns.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Gets the width of the range in number of columns and logs it to the console.
console.log(range.getWidth());

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

Integer — The number of columns in the range.

Авторизация

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

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

get Wrap()

Returns whether the text in the cell wraps. To get more granular wrap strategy, use get Wrap Strategy() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.getWrap());

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

Boolean — Whether the text in this cell wraps or not.

Авторизация

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

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

get Wrap Strategies()

Returns the text wrapping strategies for the cells in the range.

// Get the text wrapping strategies for all cells in range B5:C6
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B5:C6');
const strategies = range.getWrapStrategies();

for (let i = 0; i < strategies.length; i++) {
  for (let j = 0; j < strategies[i].length; j++) {
    Logger.log(strategies[i][j]);
  }
}

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

Wrap Strategy[][] — A two-dimensional array of text wrapping strategies.

Авторизация

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

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

get Wrap Strategy()

Returns the text wrapping strategy for the top left cell of the range.

// Get the text wrapping strategy of cell B1.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B1:D4');
Logger.log(range.getWrapStrategy());

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

Wrap Strategy — The text wrapping strategy of the top left cell in the range.

Авторизация

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

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

get Wraps()

Returns whether the text in the cells wrap. To get more granular wrap strategy, use get Wrap Strategies() .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

const results = range.getVerticalAlignments();

for (const i in results) {
  for (const j in results[i]) {
    const isWrapped = results[i][j];
    if (isWrapped) {
      Logger.log('Cell [%s, %s] has wrapped text', i, j);
    }
  }
}

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

Boolean[][] — A two-dimensional array of vertical alignments of text associated with cells in the range.

Авторизация

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

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

insert Cells(shiftDimension)

Inserts empty cells into this range. The new cells retain any formatting present in the cells previously occupying this range. Existing data in the sheet along the provided dimension is shifted away from the inserted range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:D10');
range.insertCells(SpreadsheetApp.Dimension.COLUMNS);

Параметры

Имя Тип Описание
shift Dimension Dimension The dimension along which to shift existing data.

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

Range — This range, for chaining.

Авторизация

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

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

insert Checkboxes()

Inserts checkboxes into each cell in the range, configured with true for checked and false for unchecked. Sets the value of all cells in the range to false .

const range = SpreadsheetApp.getActive().getRange('A1:B10');

// Inserts checkboxes into each cell in the range A1:B10 configured with 'true'
// for checked and 'false' for unchecked. Also, sets the value of each cell in
// the range A1:B10 to 'false'.
range.insertCheckboxes();

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

Range — This range, for chaining.

Авторизация

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

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

insert Checkboxes(checkedValue)

Inserts checkboxes into each cell in the range, configured with a custom value for checked and the empty string for unchecked. Sets the value of each cell in the range to the empty string.

const range = SpreadsheetApp.getActive().getRange('A1:B10');

// Inserts checkboxes into each cell in the range A1:B10 configured with 'yes'
// for checked and the empty string for unchecked. Also, sets the value of each
// cell in the range A1:B10 to
//  the empty string.
range.insertCheckboxes('yes');

Параметры

Имя Тип Описание
checked Value Object The checked value for the checkbox data validation.

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

Range — This range, for chaining.

Авторизация

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

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

insert Checkboxes(checkedValue, uncheckedValue)

Inserts checkboxes into each cell in the range, configured with custom values for the checked and unchecked states. Sets the value of each cell in the range to the custom unchecked value.

const range = SpreadsheetApp.getActive().getRange('A1:B10');

// Inserts checkboxes into each cell in the range A1:B10 configured with 'yes'
// for checked and 'no' for unchecked. Also, sets the value of each cell in the
// range A1:B10 to 'no'.
range.insertCheckboxes('yes', 'no');

Параметры

Имя Тип Описание
checked Value Object The checked value for the checkbox data validation.
unchecked Value Object The unchecked value for the checkbox data validation.

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

Range — This range, for chaining.

Авторизация

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

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

is Blank()

Returns true if the range is totally blank.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B2:D4');

Logger.log(range.isBlank());

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

Booleantrue if the range is blank; false otherwise.

Авторизация

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

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

is Checked()

Returns whether all cells in the range have their checkbox state as 'checked'. Returns null if some cells are checked and the rest unchecked, or if some cells do not have checkbox data validation.

const range = SpreadsheetApp.getActive().getRange('A1:A3');

// Inserts checkboxes and sets each cell value to 'no' in the range A1:A3.
range.insertCheckboxes('yes', 'no');

const range1 = SpreadsheetApp.getActive().getRange('A1');
range1.setValue('yes');
// Sets the value of isRange1Checked as true as it contains the checked value.
const isRange1Checked = range1.isChecked();

const range2 = SpreadsheetApp.getActive().getRange('A2');
range2.setValue('no');
// Sets the value of isRange2Checked as false as it contains the unchecked
// value.
const isRange2Checked = range2.isChecked();

const range3 = SpreadsheetApp.getActive().getRange('A3');
range3.setValue('random');
// Sets the value of isRange3Checked as null, as it contains an invalid checkbox
// value.
const isRange3Checked = range3.isChecked();

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

Booleantrue , if all cells in the range are checked, false if all cells in the range are unchecked, or null if any of the cells are unchecked or do not have checkbox data validation.

Авторизация

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

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

is End Column Bounded()

Determines whether the end of the range is bound to a particular column. For example, for the ranges A1:B10 or B:B , which are bound to columns at the end of the range, this method returns true ; for the ranges 3:7 or A1:5 , which are bound only to particular rows at the end of the range, this method returns false .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Determines if the end of the range is bound to a particular column and logs
// it to the console.
console.log(range.isEndColumnBounded());

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

Booleantrue if the end of the range is bound to a particular column; false otherwise.

Авторизация

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

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

is End Row Bounded()

Determines whether the end of the range is bound to a particular row. For example, for the ranges A1:B10 or 3:7 , which are bound to rows at the end of the range, this method returns true ; for the ranges B:B or A1:C , which are bound only to particular columns at the end of the range, this method returns false .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Determines if the end of the range is bound to a particular row and logs it
// to the console.
console.log(range.isEndRowBounded());

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

Booleantrue if the end of the range is bound to a particular row; false otherwise.

Авторизация

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

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

is Part Of Merge()

Returns true if the cells in the current range overlap any merged cells.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('A1:B3');

// True if any of the cells in A1:B3 is included in a merge.
const isPartOfMerge = range.isPartOfMerge();

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

Booleantrue if the range overlaps any merged cells, otherwise returns false .


is Start Column Bounded()

Determines whether the start of the range is bound to a particular column. For example, for the ranges A1:B10 or B:B , which are bound to columns at the start of the range, this method returns true ; for the range 3:7 , which is bound only to a row at the start of the range, this method returns false .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Determines if the start of the range is bound to a particular column and logs
// it to the console.
console.log(range.isStartColumnBounded());

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

Booleantrue if the start of the range is bound to a particular column; false otherwise.

Авторизация

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

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

is Start Row Bounded()

Determines whether the start of the range is bound to a particular row. For example, for the ranges A1:B10 or 3:7 , which are bound to rows at the start of the range, this method returns true ; for the range B:B , which is bound only to a particular column at the start of the range, this method returns false .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range A1:D10 on Sheet1.
const range = sheet.getRange('A1:D10');

// Determines if the start of the range is bound to a particular row and logs it
// to the console.
console.log(range.isStartRowBounded());

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

Booleantrue if the start of the range is bound to a particular row; false otherwise.

Авторизация

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

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

merge()

Merges the cells in the range together into a single block.

const sheet = SpreadsheetApp.getActiveSheet();

// The code below 2-dimensionally merges the cells in A1 to B3
sheet.getRange('A1:B3').merge();

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

Range — This range, for chaining.

Авторизация

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

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

merge Across()

Merge the cells in the range across the columns of the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The code below merges cells C5:E5 into one cell
const range1 = sheet.getRange('C5:E5');
range1.mergeAcross();

// The code below creates 2 horizontal cells, F5:H5 and F6:H6
const range2 = sheet.getRange('F5:H6');
range2.mergeAcross();

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

Range — This range, for chaining.

Авторизация

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

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

merge Vertically()

Merges the cells in the range together.

const sheet = SpreadsheetApp.getActiveSheet();

// The code below vertically merges the cells in A1 to A10
sheet.getRange('A1:A10').mergeVertically();

// The code below creates 3 merged columns: B1 to B10, C1 to C10, and D1 to D10
sheet.getRange('B1:D10').mergeVertically();

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

Range — This range, for chaining.

Авторизация

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

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

move To(target)

Cut and paste (both format and values) from this range to the target range.

// The code below moves the first 5 columns over to the 6th column
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A1:E').moveTo(sheet.getRange('F1'));

Параметры

Имя Тип Описание
target Range A target range to copy this range to; only the top-left cell position is relevant.

Авторизация

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

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

offset(rowOffset, columnOffset)

Returns a new range that is offset from this range by the given number of rows and columns (which can be negative). The new range is the same size as the original range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('A1');

// newCell references B2
const newCell = cell.offset(1, 1);

Параметры

Имя Тип Описание
row Offset Integer The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
column Offset Integer The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.

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

Range — This range, for chaining.


offset(rowOffset, columnOffset, numRows)

Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height in cells.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('A1');

// newCell references B2:B3
const newRange = cell.offset(1, 1, 2);

Параметры

Имя Тип Описание
row Offset Integer The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
column Offset Integer The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
num Rows Integer The height in rows of the new range.

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

Range — This range, for chaining.


offset(rowOffset, columnOffset, numRows, numColumns)

Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height and width in cells.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('A1');

// newCell references B2:C3
const newRange = cell.offset(1, 1, 2, 2);

Параметры

Имя Тип Описание
row Offset Integer The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
column Offset Integer The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
num Rows Integer The height in rows of the new range.
num Columns Integer The width in columns of the new range.

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

Range — This range, for chaining.


protect()

Creates an object that can protect the range from being edited except by users who have permission. Until the script actually changes the list of editors for the range (by calling Protection.removeEditor(emailAddress) , Protection.removeEditor(user) , Protection.removeEditors(emailAddresses) , Protection.addEditor(emailAddress) , Protection.addEditor(user) , Protection.addEditors(emailAddresses) , or setting a new value for Protection.setDomainEdit(editable) ), the permissions mirror those of the spreadsheet itself, which effectively means that the range remains unprotected. If the range is already protected, this method creates a new protected range that overlaps the existing one. If a cell is protected by multiple protected ranges and any of them prevent a particular user from editing the cell, then that user is not permitted to edit the cell.

// Protect range A1:B10, then remove all other users from the list of editors.
const ss = SpreadsheetApp.getActive();
const range = ss.getRange('A1:B10');
const protection = range.protect().setDescription('Sample protected range');

// Ensure the current user is an editor before removing others. Otherwise, if
// the user's edit permission comes from a group, the script throws an exception
// upon removing the group.
const me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

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

Protection — An object representing the protection settings.

Авторизация

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

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

randomize()

Randomizes the order of the rows in the given range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('A1:C7');

// Randomizes the range
range.randomize();

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

Range — This range, for chaining.

Авторизация

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

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

remove Checkboxes()

Removes all checkboxes from the range. Clears the data validation of each cell, and additionally clears its value if the cell contains either the checked or unchecked value.

const range = SpreadsheetApp.getActive().getRange('A1:B10');

// Inserts checkboxes and sets each cell value to 'no' in the range A1:B10.
range.insertCheckboxes('yes', 'no');

const range1 = SpreadsheetApp.getActive().getRange('A1');
range1.setValue('yes');
// Removes the checkbox data validation in cell A1 and clears its value.
range1.removeCheckboxes();

const range2 = SpreadsheetApp.getActive().getRange('A2');
range2.setValue('random');
// Removes the checkbox data validation in cell A2 but does not clear its value.
range2.removeCheckboxes();

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

Range — This range, for chaining.

Авторизация

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

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

remove Duplicates()

Removes rows within this range that contain values that are duplicates of values in any previous row. Rows with identical values but different letter cases, formatting, or formulas are considered to be duplicates. This method also removes duplicates rows hidden from view (for example, due to a filter). Content outside of this range isn't removed.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B1:D7');

// Remove duplicate rows in the range.
range.removeDuplicates();

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

Range — The resulting range after removing duplicates. The size of the range is reduced by a row for every row removed.

Авторизация

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

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

remove Duplicates(columnsToCompare)

Removes rows within this range that contain values in the specified columns that are duplicates of values any previous row. Rows with identical values but different letter cases, formatting, or formulas are considered to be duplicates. This method also removes duplicates rows hidden from view (for example, due to a filter). Content outside of this range isn't removed.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('B1:D7');

// Remove rows which have duplicate values in column B.
range.removeDuplicates([2]);

// Remove rows which have duplicate values in both columns B and D.
range.removeDuplicates([2, 4]);

Параметры

Имя Тип Описание
columns To Compare Integer[] The columns to analyze for duplicate values. If no columns are provided then all columns are analyzed for duplicates.

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

Range — The resulting range after removing duplicates. The size of the range is reduced by a row for every row removed.

Авторизация

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

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

set Background(color)

Sets the background color of all cells in the range in CSS notation (such as '#ffffff' or 'white' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const range = sheet.getRange('B2:D5');
range.setBackground('red');

Параметры

Имя Тип Описание
color String A color code in CSS notation (such as '#ffffff' or 'white' ); a null value resets the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Background Object(color)

Sets the background color of all cells in the range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const bgColor = SpreadsheetApp.newColor()
                    .setThemeColor(SpreadsheetApp.ThemeColorType.BACKGROUND)
                    .build();

const range = sheet.getRange('B2:D5');
range.setBackgroundObject(bgColor);

Параметры

Имя Тип Описание
color Color The background color to set; null value resets the background color.

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

Range — This range, for chaining.

Авторизация

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

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

set Background Objects(color)

Sets a rectangular grid of background colors (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const colorAccent1 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT1)
                         .build();
const colorAccent2 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT2)
                         .build();
const colorAccent3 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT3)
                         .build();
const colorAccent4 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT4)
                         .build();

const colors = [
  [colorAccent1, colorAccent2],
  [colorAccent3, colorAccent4],
];

const cell = sheet.getRange('B5:C6');
cell.setBackgroundObjects(colors);

Параметры

Имя Тип Описание
color Color[][] A two-dimensional array of colors; null values reset the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Background RGB(red, green, blue)

Sets the background to the given color using RGB values (integers between 0 and 255 inclusive).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');

// Sets the background to white
cell.setBackgroundRGB(255, 255, 255);

// Sets the background to red
cell.setBackgroundRGB(255, 0, 0);

Параметры

Имя Тип Описание
red Integer The red value in RGB notation.
green Integer The green value in RGB notation.
blue Integer The blue value in RGB notation.

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

Range — This range, for chaining.

Авторизация

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

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

set Backgrounds(color)

Sets a rectangular grid of background colors (must match dimensions of this range). The colors are in CSS notation (such as '#ffffff' or 'white' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const colors = [
  ['red', 'white', 'blue'],
  ['#FF0000', '#FFFFFF', '#0000FF'],  // These are the hex equivalents
];

const cell = sheet.getRange('B5:D6');
cell.setBackgrounds(colors);

Параметры

Имя Тип Описание
color String[][] A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white' ); null values reset the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Border(top, left, bottom, right, vertical, horizontal)

Sets the border property. Valid values are true (on), false (off) and null (no change).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
// Sets borders on the top and bottom, but leaves the left and right unchanged
cell.setBorder(true, null, true, null, false, false);

Параметры

Имя Тип Описание
top Boolean true for border, false for none, null for no change.
left Boolean true for border, false for none, null for no change.
bottom Boolean true for border, false for none, null for no change.
right Boolean true for border, false for none, null for no change.
vertical Boolean true for internal vertical borders, false for none, null for no change.
horizontal Boolean true for internal horizontal borders, false for none, null for no change.

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

Range — This range, for chaining.

Авторизация

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

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

set Border(top, left, bottom, right, vertical, horizontal, color, style)

Sets the border property with color and/or style. Valid values are true (on), false (off) and null (no change). For color, use Color in CSS notation (such as '#ffffff' or 'white' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
// Sets borders on the top and bottom, but leaves the left and right unchanged
// Also sets the color to "red", and the border to "DASHED".
cell.setBorder(
    true,
    null,
    true,
    null,
    false,
    false,
    'red',
    SpreadsheetApp.BorderStyle.DASHED,
);

Параметры

Имя Тип Описание
top Boolean true for border, false for none, null for no change.
left Boolean true for border, false for none, null for no change.
bottom Boolean true for border, false for none, null for no change.
right Boolean true for border, false for none, null for no change.
vertical Boolean true for internal vertical borders, false for none, null for no change.
horizontal Boolean true for internal horizontal borders, false for none, null for no change.
color String A color in CSS notation (such as '#ffffff' or 'white' ), null for default color (black).
style Border Style A style for the borders, null for default style (solid).

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

Range — This range, for chaining.

Авторизация

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

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

set Data Validation(rule)

Sets one data validation rule for all cells in the range.

// Set the data validation rule for cell A1 to require a value from B1:B10.
const cell = SpreadsheetApp.getActive().getRange('A1');
const range = SpreadsheetApp.getActive().getRange('B1:B10');
const rule =
    SpreadsheetApp.newDataValidation().requireValueInRange(range).build();
cell.setDataValidation(rule);

Параметры

Имя Тип Описание
rule Data Validation The data validation rule to set, or null to remove data validation.

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

Range — This range, for chaining.

Авторизация

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

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

set Data Validations(rules)

Sets the data validation rules for all cells in the range. This method takes a two-dimensional array of data validations, indexed by row then by column. The array dimensions must correspond to the range dimensions.

// Set the data validation rules for Sheet1!A1:B5 to require a value from
// Sheet2!A1:A10.
const destinationRange =
    SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange('A1:B5');
const sourceRange =
    SpreadsheetApp.getActive().getSheetByName('Sheet2').getRange('A1:A10');
const rule =
    SpreadsheetApp.newDataValidation().requireValueInRange(sourceRange).build();
const rules = destinationRange.getDataValidations();
for (let i = 0; i < rules.length; i++) {
  for (let j = 0; j < rules[i].length; j++) {
    rules[i][j] = rule;
  }
}
destinationRange.setDataValidations(rules);

Параметры

Имя Тип Описание
rules Data Validation[][] A two-dimensional array of data validation rules to set; null values remove data validation.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Color(color)

Sets the font color in CSS notation (such as '#ffffff' or 'white' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontColor('red');

Параметры

Имя Тип Описание
color String The font color in CSS notation (such as '#ffffff' or 'white' ); a null value resets the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Color Object(color)

Sets the font color of the given range.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const color = SpreadsheetApp.newColor()
                  .setThemeColor(SpreadsheetApp.ThemeColorType.TEXT)
                  .build();

const cell = sheet.getRange('B2');
cell.setFontColor(color);

Параметры

Имя Тип Описание
color Color The font color to set; a null value resets the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Color Objects(colors)

Sets a rectangular grid of font colors (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const colorAccent1 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT1)
                         .build();
const colorAccent2 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT2)
                         .build();
const colorAccent3 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT3)
                         .build();
const colorAccent4 = SpreadsheetApp.newColor()
                         .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT4)
                         .build();

const colors = [
  [colorAccent1, colorAccent2],
  [colorAccent3, colorAccent4],
];

const cell = sheet.getRange('B5:C6');
cell.setFontColorObjects(colors);

Параметры

Имя Тип Описание
colors Color[][] A two-dimensional array of colors; null values reset the font color.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Colors(colors)

Sets a rectangular grid of font colors (must match dimensions of this range). The colors are in CSS notation (such as '#ffffff' or 'white' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const colors = [
  ['red', 'white', 'blue'],
  ['#FF0000', '#FFFFFF', '#0000FF'],  // These are the hex equivalents
];

const cell = sheet.getRange('B5:D6');
cell.setFontColors(colors);

Параметры

Имя Тип Описание
colors Object[][] A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white' ); null values reset the color.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Families(fontFamilies)

Sets a rectangular grid of font families (must match dimensions of this range). Examples of font families are "Arial" or "Helvetica".

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const fonts = [
  ['Arial', 'Helvetica', 'Verdana'],
  ['Courier New', 'Arial', 'Helvetica'],
];

const cell = sheet.getRange('B2:D3');
cell.setFontFamilies(fonts);

Параметры

Имя Тип Описание
font Families Object[][] A two-dimensional array of font families; null values reset the font family.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Family(fontFamily)

Sets the font family, such as "Arial" or "Helvetica".

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontFamily('Helvetica');

Параметры

Имя Тип Описание
font Family String The font family to set; a null value resets the font family.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Line(fontLine)

Sets the font line style of the given range ( 'underline' , 'line-through' , or 'none' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontLine('line-through');

Параметры

Имя Тип Описание
font Line String The font line style, either 'underline' , 'line-through' , or 'none' ; a null value resets the font line style.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Lines(fontLines)

Sets a rectangular grid of line styles (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const fontLines = [['underline', 'line-through', 'none']];

const range = sheet.getRange('B2:D2');
range.setFontLines(fontLines);

Параметры

Имя Тип Описание
font Lines Object[][] A two-dimensional array of font line styles ( 'underline' , 'line-through' , or 'none' ); null values reset the font line style.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Size(size)

Sets the font size, with the size being the point size to use.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontSize(20);

Параметры

Имя Тип Описание
size Integer A font size in point size.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Sizes(sizes)

Sets a rectangular grid of font sizes (must match dimensions of this range). The sizes are in points.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const fontSizes = [[16, 20, 24]];

const range = sheet.getRange('B2:D2');
range.setFontSizes(fontSizes);

Параметры

Имя Тип Описание
sizes Object[][] A two-dimensional array of sizes.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Font Style(fontStyle)

Set the font style for the given range ( 'italic' or 'normal' ).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontStyle('italic');

Параметры

Имя Тип Описание
font Style String The font style, either 'italic' or 'normal' ; a null value resets the font style.

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

Range — This range, for chaining.

Авторизация

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

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

set Font Styles(fontStyles)

Sets a rectangular grid of font styles (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const fontStyles = [['italic', 'normal']];

const range = sheet.getRange('B2:C2');
range.setFontStyles(fontStyles);

Параметры

Имя Тип Описание
font Styles Object[][] A two-dimensional array of font styles, either 'italic' or 'normal' ; null values reset the font style.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Font Weight(fontWeight)

Set the font weight for the given range (normal/bold).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setFontWeight('bold');

Параметры

Имя Тип Описание
font Weight String The font weight, either 'bold' or 'normal' ; a null value resets the font weight.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Font Weights(fontWeights)

Sets a rectangular grid of font weights (must match dimensions of this range). An example of a font weight is "bold".

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const fontStyles = [['bold', 'bold', 'normal']];

const range = sheet.getRange('B2:D2');
range.setFontWeights(fontStyles);

Параметры

Имя Тип Описание
font Weights Object[][] A two-dimensional array of font weights, either 'bold' or 'normal' ; null values reset the font weight.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Formula(formula)

Updates the formula for this range. The given formula must be in A1 notation.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B5');
cell.setFormula('=SUM(B3:B4)');

Параметры

Имя Тип Описание
formula String A string representing the formula to set for the cell.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Formula R1C1(formula)

Updates the formula for this range. The given formula must be in R1C1 notation.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B5');
// This sets the formula to be the sum of the 3 rows above B5
cell.setFormulaR1C1('=SUM(R[-3]C[0]:R[-1]C[0])');

Параметры

Имя Тип Описание
formula String A string formula.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Formulas(formulas)

Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in A1 notation. This method takes a two-dimensional array of formulas, indexed by row, then by column. The array dimensions must correspond to the range dimensions.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// This sets the formulas to be a row of sums, followed by a row of averages
// right below. The size of the two-dimensional array must match the size of the
// range.
const formulas = [
  ['=SUM(B2:B4)', '=SUM(C2:C4)', '=SUM(D2:D4)'],
  ['=AVERAGE(B2:B4)', '=AVERAGE(C2:C4)', '=AVERAGE(D2:D4)'],
];

const cell = sheet.getRange('B5:D6');
cell.setFormulas(formulas);

Параметры

Имя Тип Описание
formulas String[][] A two-dimensional string array of formulas.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Formulas R1C1(formulas)

Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in R1C1 notation.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// This creates formulas for a row of sums, followed by a row of averages.
const sumOfRowsAbove = '=SUM(R[-3]C[0]:R[-1]C[0])';
const averageOfRowsAbove = '=AVERAGE(R[-4]C[0]:R[-2]C[0])';

// The size of the two-dimensional array must match the size of the range.
const formulas = [
  [sumOfRowsAbove, sumOfRowsAbove, sumOfRowsAbove],
  [averageOfRowsAbove, averageOfRowsAbove, averageOfRowsAbove],
];

const cell = sheet.getRange('B5:D6');
// This sets the formula to be the sum of the 3 rows above B5.
cell.setFormulasR1C1(formulas);

Параметры

Имя Тип Описание
formulas String[][] A two-dimensional array of formulas in R1C1 format.

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

Range — This range, for chaining.

Авторизация

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

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

set Horizontal Alignment(alignment)

Set the horizontal (left to right) alignment for the given range (left/center/right).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setHorizontalAlignment('center');

Параметры

Имя Тип Описание
alignment String The alignment, either 'left' , 'center' or 'normal' ; a null value resets the alignment.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Horizontal Alignments(alignments)

Sets a rectangular grid of horizontal alignments. see set Horizontal Alignment(alignment)

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const horizontalAlignments = [['left', 'right', 'center']];

const range = sheet.getRange('B2:D2');
range.setHorizontalAlignments(horizontalAlignments);

Параметры

Имя Тип Описание
alignments Object[][] A two-dimensional array of alignments, either 'left' , 'center' or 'normal' ; a null value resets the alignment.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

См. также


set Note(note)

Sets the note to the given value.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setNote('This is a note');

Параметры

Имя Тип Описание
note String The note value to set for the range; a null value removes the note.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Notes(notes)

Sets a rectangular grid of notes (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const notes = [
  ['it goes', 'like this', 'the fourth, the fifth'],
  ['the minor fall', 'and the', 'major lift'],
];

const cell = sheet.getRange('B2:D3');
cell.setNotes(notes);

Параметры

Имя Тип Описание
notes Object[][] A two-dimensional array of notes; null values remove the note.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

См. также


set Number Format(numberFormat)

Sets the number or date format to the given formatting string. The accepted format patterns are described in the Sheets API documentation .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
// Always show 3 decimal points
cell.setNumberFormat('0.000');

Параметры

Имя Тип Описание
number Format String A number format string.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Number Formats(numberFormats)

Sets a rectangular grid of number or date formats (must match dimensions of this range). The values are format pattern strings as described in the Sheets API documentation .

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const formats = [['0.000', '0,000,000', '$0.00']];

const range = sheet.getRange('B2:D2');
range.setNumberFormats(formats);

Параметры

Имя Тип Описание
number Formats Object[][] A two-dimensional array of number formats.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Rich Text Value(value)

Sets the Rich Text value for the cells in the range.

// Sets all cells in range B2:D4 to have the text "Hello world", with "Hello"
// bolded.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B2:D4');
const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
const richText = SpreadsheetApp.newRichTextValue()
                     .setText('Hello world')
                     .setTextStyle(0, 5, bold)
                     .build();
range.setRichTextValue(richText);

Параметры

Имя Тип Описание
value Rich Text Value The desired Rich Text value.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Rich Text Values(values)

Sets a rectangular grid of Rich Text values.

// Sets the cells in range A1:A2 to have Rich Text values.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('A1:A2');
const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
const italic = SpreadsheetApp.newTextStyle().setItalic(true).build();
const richTextA1 = SpreadsheetApp.newRichTextValue()
                       .setText('This cell is bold')
                       .setTextStyle(bold)
                       .build();
const richTextA2 = SpreadsheetApp.newRichTextValue()
                       .setText('bold words, italic words')
                       .setTextStyle(0, 11, bold)
                       .setTextStyle(12, 24, italic)
                       .build();
range.setRichTextValues([[richTextA1], [richTextA2]]);

Параметры

Имя Тип Описание
values Rich Text Value[][] The desired Rich Text values.

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

Range — This range, for chaining.

Авторизация

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

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

Sets whether or not the range should show hyperlinks.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can useSpreadsheetApp.getActiveSpreadsheet()
// instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Gets Sheet1 by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets cell A30 and sets its hyperlink value.
const range = sheet.getRange('A30');
range.setValue('https://www.example.com');

// Sets cell A30 to show hyperlinks.
range.setShowHyperlink(true);

Параметры

Имя Тип Описание
show Hyperlink Boolean Whether or not to show the hyperlink.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Direction(direction)

Sets the text direction for the cells in the range. If a specified direction is null , the direction is inferred and then set.

// Sets right-to-left text direction for the range.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B5:C6');
range.setTextDirection(SpreadsheetApp.TextDirection.RIGHT_TO_LEFT);

Параметры

Имя Тип Описание
direction Text Direction The desired text direction; if null the direction is inferred before setting.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Directions(directions)

Sets a rectangular grid of text directions. If a specified direction is null , the direction is inferred and then set.

// Copies all of the text directions from range A1:B2 over to range C5:D6.
const sheet = SpreadsheetApp.getActiveSheet();
const range1 = sheet.getRange('A1:B2');
const range2 = sheet.getRange('C5:D6');

range2.setTextRotations(range1.getTextDirections());

Параметры

Имя Тип Описание
directions Text Direction[][] The desired text directions; if a specified direction is null it is inferred before setting.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Rotation(degrees)

Sets the text rotation settings for the cells in the range. The input corresponds to the angle between the standard text orientation and the desired orientation. An input of zero indicates that the text is set to the standard orientation.

For left to right text direction, positive angles are in the counterclockwise direction, whereas for right to left they are in the clockwise direction.

// Sets all cell's in range B2:D4 to have text rotated up 45 degrees.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B2:D4');

range.setTextRotation(45);

Параметры

Имя Тип Описание
degrees Integer The desired angle between the standard orientation and the desired orientation. For left to right text, positive angles are in the counterclockwise direction.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Rotation(rotation)

Sets the text rotation settings for the cells in the range.

// Sets all cell's in range B2:D4 to have the same text rotation settings as
// cell A1.
const sheet = SpreadsheetApp.getActiveSheet();

const rotation = sheet.getRange('A1').getTextRotation();

sheet.getRange('B2:D4').setTextRotation(rotation);

Параметры

Имя Тип Описание
rotation Text Rotation The desired text rotation settings.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Rotations(rotations)

Sets a rectangular grid of text rotations.

// Copies all of the text rotations from range A1:B2 over to range C5:D6.
const sheet = SpreadsheetApp.getActiveSheet();
const range1 = sheet.getRange('A1:B2');
const range2 = sheet.getRange('C5:D6');

range2.setTextRotations(range1.getTextRotations());

Параметры

Имя Тип Описание
rotations Text Rotation[][] The desired text rotation settings.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Style(style)

Sets the text style for the cells in the range.

// Sets the cells in range C5:D6 to have underlined size 15 font.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('C5:D6');
const style =
    SpreadsheetApp.newTextStyle().setFontSize(15).setUnderline(true).build();
range.setTextStyle(style);

Параметры

Имя Тип Описание
style Text Style The desired text style.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Text Styles(styles)

Sets a rectangular grid of text styles.

// Sets text styles for cells in range A1:B2
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('A1:B2');
const bold = SpreadsheetApp.newTextStyle().setBold(true).build();
const otherStyle = SpreadsheetApp.newTextStyle()
                       .setBold(true)
                       .setUnderline(true)
                       .setItalic(true)
                       .setForegroundColor('#335522')
                       .setFontSize(44)
                       .build();
range.setTextStyles([
  [bold, otherStyle],
  [otherStyle, bold],
]);

Параметры

Имя Тип Описание
styles Text Style[][] The desired text styles.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Value(value)

Sets the value of the range. The value can be numeric, string, boolean or date. If it begins with '=' it is interpreted as a formula.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setValue(100);

Параметры

Имя Тип Описание
value Object The value for the range.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Values(values)

Sets a rectangular grid of values (must match dimensions of this range). If a value begins with = , it's interpreted as a formula.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const values = [['2.000', '1,000,000', '$2.99']];

const range = sheet.getRange('B2:D2');
range.setValues(values);

Параметры

Имя Тип Описание
values Object[][] A two-dimensional array of values.

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

Range — This range, for chaining.

Авторизация

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

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

set Vertical Alignment(alignment)

Set the vertical (top to bottom) alignment for the given range (top/middle/bottom).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setVerticalAlignment('middle');

Параметры

Имя Тип Описание
alignment String The alignment, either 'top' , 'middle' or 'bottom' ; a null value resets the alignment.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Vertical Alignments(alignments)

Sets a rectangular grid of vertical alignments (must match dimensions of this range).

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const alignments = [['top', 'middle', 'bottom']];

const range = sheet.getRange('B2:D2');
range.setVerticalAlignments(alignments);

Параметры

Имя Тип Описание
alignments Object[][] A two-dimensional array of alignments, either 'top' , 'middle' or 'bottom' ; a null value resets the alignment.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

См. также


set Vertical Text(isVertical)

Sets whether or not to stack the text for the cells in the range. If the text is stacked vertically, the degree text rotation setting is ignored.

// Sets all cell's in range B2:D4 to have vertically stacked text.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B2:D4');

range.setVerticalText(true);

Параметры

Имя Тип Описание
is Vertical Boolean Whether or not to stack the text.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Wrap(isWrapEnabled)

Set the cell wrap of the given range.

Cells with wrap enabled (the default) resize to display their full content. Cells with wrap disabled display as much as possible in the cell without resizing or running to multiple lines.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

const cell = sheet.getRange('B2');
cell.setWrap(true);

Параметры

Имя Тип Описание
is Wrap Enabled Boolean Whether to wrap text or not.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Wrap Strategies(strategies)

Sets a rectangular grid of wrap strategies.

// Copies all of the wrap strategies from range A1:B2 over to range C5:D6.
const sheet = SpreadsheetApp.getActiveSheet();
const range1 = sheet.getRange('A1:B2');
const range2 = sheet.getRange('C5:D6');

range2.setWrapStrategies(range1.getWrapStrategies());

Параметры

Имя Тип Описание
strategies Wrap Strategy[][] The desired wrapping strategies.

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

Range — This range, for chaining.

Авторизация

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

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

set Wrap Strategy(strategy)

Sets the text wrapping strategy for the cells in the range.

// Sets all cells in range B2:D4 to use the clip wrap strategy.
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('B2:D4');

range.setWrapStrategy(SpreadsheetApp.WrapStrategy.CLIP);

Параметры

Имя Тип Описание
strategy Wrap Strategy The desired wrapping strategy.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

set Wraps(isWrapEnabled)

Sets a rectangular grid of word wrap policies (must match dimensions of this range). Cells with wrap enabled (the default) resize to display their full content. Cells with wrap disabled display as much as possible in the cell without resizing or running to multiple lines.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];

// The size of the two-dimensional array must match the size of the range.
const wraps = [[true, true, false]];

const range = sheet.getRange('B2:D2');
range.setWraps(wraps);

Параметры

Имя Тип Описание
is Wrap Enabled Object[][] A two-dimensional array of wrap variables that determine whether to wrap text in a cell or not.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

См. также


shift Column Group Depth(delta)

Changes the column grouping depth of the range by the specified amount.

This has the effect of creating, modifying, or deleting groups that intersect with the range. For positive deltas, groups are created and/or modified; for negative deltas, groups are destroyed and/or modified.

This has no effect when decreasing the group depth below zero or above eight.

If the column group control position is BEFORE , this throws an error when attempting to shift the depth of the first row.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getActiveRange();

// The column grouping depth is increased by 1.
range.shiftColumnGroupDepth(1);

// The column grouping depth is decreased by 1.
range.shiftColumnGroupDepth(-1);

Параметры

Имя Тип Описание
delta Integer The amount by which to change the column group depth of this range.

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

Range — This range, for chaining.

Броски

Error — when attempting to shift the depth of the first column when the control position is Group Control Toggle Position.BEFORE

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

shift Row Group Depth(delta)

Changes the row grouping depth of the range by the specified amount.

This has the effect of creating, modifying, or deleting groups that intersect with the range. For positive deltas, groups are created and/or modified; for negative deltas, groups are destroyed and/or modified.

This has no effect when decreasing the group depth below zero or above eight.

If the row group control position is BEFORE , this throws an error when attempting to shift the depth of the first row.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getActiveRange();

// The row grouping depth is increased by 1.
range.shiftRowGroupDepth(1);

// The row grouping depth is decreased by 1.
range.shiftRowGroupDepth(-1);

Параметры

Имя Тип Описание
delta Integer The amount by which to change the row group depth of this range.

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

Range — This range, for chaining.

Броски

Error — when attempting to shift the depth of the first row when the control position is Group Control Toggle Position.BEFORE

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

sort(sortSpecObj)

Sorts the cells in the given range, by column and order specified.

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
const range = sheet.getRange('A1:C7');

// Sorts by the values in the first column (A)
range.sort(1);

// Sorts by the values in the second column (B)
range.sort(2);

// Sorts descending by column B
range.sort({column: 2, ascending: false});

// Sorts descending by column B, then ascending by column A
// Note the use of an array
range.sort([
  {column: 2, ascending: false},
  {column: 1, ascending: true},
]);

// For rows that are sorted in ascending order, the "ascending" parameter is
// optional, and just an integer with the column can be used instead. Note that
// in general, keeping the sort specification consistent results in more
// readable code. You can express the earlier sort as:
range.sort([{column: 2, ascending: false}, 1]);

// Alternatively, if you want all columns to be in ascending order, you can use
// the following (this makes column 2 ascending)
range.sort([2, 1]);
// ... which is equivalent to
range.sort([
  {column: 2, ascending: true},
  {column: 1, ascending: true},
]);

Параметры

Имя Тип Описание
sort Spec Obj Object The columns to sort by.

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

split Text To Columns()

Splits a column of text into multiple columns based on an auto-detected delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one,one,one      |                 |                 |
// 2 |two,two,two      |                 |                 |
// 3 |three,three,three|                 |                 |

const range = SpreadsheetApp.getActiveSheet().getRange('A1:A3');
range.splitTextToColumns();

// Result after splitting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

split Text To Columns(delimiter)

Splits a column of text into multiple columns using the specified string as a custom delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one#one#one      |                 |                 |
// 2 |two#two#two      |                 |                 |
// 3 |three#three#three|                 |                 |

const range = SpreadsheetApp.getActiveSheet().getRange('A1:A3');
range.splitTextToColumns('#');

// Result after splitting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Параметры

Имя Тип Описание
delimiter String The custom delimiter to split on.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

split Text To Columns(delimiter)

Splits a column of text into multiple columns based on the specified delimiter.

// A1:A3 has the following values:
//           A                  B                 C
// 1 |one;one;one      |                 |                 |
// 2 |two;two;two      |                 |                 |
// 3 |three;three;three|                 |                 |

const range = SpreadsheetApp.getActiveSheet().getRange('A1:A3');
range.splitTextToColumns(SpreadsheetApp.TextToColumnsDelimiter.SEMICOLON);

// Result after splitting the text to columns:
//           A                  B                 C
// 1 |one              |one              |one              |
// 2 |two              |two              |two              |
// 3 |three            |three            |three            |

Параметры

Имя Тип Описание
delimiter Text To Columns Delimiter The preset delimiter to split on.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

trim Whitespace()

Trims the whitespace (such as spaces, tabs, or new lines) in every cell in this range. Removes all whitespace from the start and end of each cell's text, and reduces any subsequence of remaining whitespace characters to a single space.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const range = sheet.getRange('A1:A4');
range.activate();
range.setValues([
  ' preceding space',
  'following space ',
  'two  middle  spaces',
  '   =SUM(1,2)',
]);

range.trimWhitespace();

const values = range.getValues();
// Values are ['preceding space', 'following space', 'two middle spaces',
// '=SUM(1,2)']

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

uncheck()

Changes the state of the checkboxes in the range to “unchecked”. Ignores the cells in the range which currently do not contain either the checked or unchecked value configured.

// Changes the state of cells which currently contain either the checked or
// unchecked value configured in the range A1:B10 to 'unchecked'.
const range = SpreadsheetApp.getActive().getRange('A1:B10');
range.uncheck();

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

Range — This range, for chaining.

Авторизация

Scripts that use this method require authorization with one or more of the following scopes :

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

Устаревшие методы