Доступ и изменение диапазонов электронных таблиц. Диапазон может быть отдельной ячейкой на листе или группой смежных ячеек на листе.
Методы
Метод | Тип возврата | Краткое описание |
---|---|---|
activate() | Range | Устанавливает указанный диапазон в качестве active range , при этом верхняя левая ячейка в диапазоне является current cell . |
activateAsCurrentCell() | Range | Устанавливает указанную ячейку в качестве current cell . |
addDeveloperMetadata(key) | Range | Добавляет метаданные разработчика с указанным ключом в диапазон. |
addDeveloperMetadata(key, visibility) | Range | Добавляет метаданные разработчика с указанным ключом и видимостью в диапазон. |
addDeveloperMetadata(key, value) | Range | Добавляет метаданные разработчика с указанным ключом и значением в диапазон. |
addDeveloperMetadata(key, value, visibility) | Range | Добавляет метаданные разработчика с указанным ключом, значением и видимостью в диапазон. |
applyColumnBanding() | Banding | Применяет тему чередования столбцов по умолчанию к диапазону. |
applyColumnBanding(bandingTheme) | Banding | Применяет указанную тему чередования столбцов к диапазону. |
applyColumnBanding(bandingTheme, showHeader, showFooter) | Banding | Применяет указанную тему чередования столбцов к диапазону с указанными настройками верхнего и нижнего колонтитула. |
applyRowBanding() | Banding | Применяет тему объединения строк по умолчанию к диапазону. |
applyRowBanding(bandingTheme) | Banding | Применяет указанную тему объединения строк к диапазону. |
applyRowBanding(bandingTheme, showHeader, showFooter) | Banding | Применяет указанную тему чередования строк к диапазону с указанными настройками верхнего и нижнего колонтитула. |
autoFill(destination, series) | void | Заполняет destinationRange данными на основе данных в этом диапазоне. |
autoFillToNeighbor(series) | void | Вычисляет диапазон для заполнения новыми данными на основе соседних ячеек и автоматически заполняет этот диапазон новыми значениями на основе данных, содержащихся в этом диапазоне. |
breakApart() | Range | Снова разбейте все ячейки с несколькими столбцами в диапазоне на отдельные ячейки. |
canEdit() | Boolean | Определяет, есть ли у пользователя разрешение на редактирование каждой ячейки в диапазоне. |
check() | Range | Изменяет состояние флажков в диапазоне на «отмечено». |
clear() | Range | Очищает диапазон содержимого и форматов. |
clear(options) | Range | Очищает диапазон содержимого, формат, правила проверки данных и/или комментарии, как указано с заданными дополнительными параметрами. |
clearContent() | Range | Очищает содержимое диапазона, оставляя форматирование нетронутым. |
clearDataValidations() | Range | Очищает правила проверки данных для диапазона. |
clearFormat() | Range | Очищает форматирование для этого диапазона. |
clearNote() | Range | Очищает заметку в указанной ячейке или ячейках. |
collapseGroups() | Range | Сворачивает все группы, которые полностью входят в диапазон. |
copyFormatToRange(gridId, column, columnEnd, row, rowEnd) | void | Скопируйте форматирование диапазона в указанное место. |
copyFormatToRange(sheet, column, columnEnd, row, rowEnd) | void | Скопируйте форматирование диапазона в указанное место. |
copyTo(destination) | void | Копирует данные из диапазона ячеек в другой диапазон ячеек. |
copyTo(destination, copyPasteType, transposed) | void | Копирует данные из диапазона ячеек в другой диапазон ячеек. |
copyTo(destination, options) | void | Копирует данные из диапазона ячеек в другой диапазон ячеек. |
copyValuesToRange(gridId, column, columnEnd, row, rowEnd) | void | Скопируйте содержимое диапазона в указанное место. |
copyValuesToRange(sheet, column, columnEnd, row, rowEnd) | void | Скопируйте содержимое диапазона в указанное место. |
createDataSourcePivotTable(dataSource) | DataSourcePivotTable | Создает пустую сводную таблицу источника данных из источника данных, привязанную к первой ячейке в этом диапазоне. |
createDataSourceTable(dataSource) | DataSourceTable | Создает пустую таблицу источника данных из источника данных, привязанную к первой ячейке в этом диапазоне. |
createDeveloperMetadataFinder() | DeveloperMetadataFinder | Возвращает DeveloperMetadataFinderApi для поиска метаданных разработчика в рамках этого диапазона. |
createFilter() | Filter | Создает фильтр и применяет его к указанному диапазону на листе. |
createPivotTable(sourceData) | PivotTable | Создает пустую сводную таблицу из указанных sourceData , привязанных к первой ячейке в этом диапазоне. |
createTextFinder(findText) | TextFinder | Создает средство поиска текста для диапазона, которое может найти и заменить текст в этом диапазоне. |
deleteCells(shiftDimension) | void | Удаляет этот диапазон ячеек. |
expandGroups() | Range | Разворачивает свернутые группы, диапазон которых или переключатель управления пересекаются с этим диапазоном. |
getA1Notation() | String | Возвращает строковое описание диапазона в нотации A1. |
getBackground() | String | Возвращает цвет фона верхней левой ячейки в диапазоне (например, '#ffffff' ). |
getBackgroundObject() | Color | Возвращает цвет фона верхней левой ячейки диапазона. |
getBackgroundObjects() | Color[][] | Возвращает цвета фона ячеек в диапазоне. |
getBackgrounds() | String[][] | Возвращает цвета фона ячеек в диапазоне (например, '#ffffff' ). |
getBandings() | Banding[] | Возвращает все полосы, которые применяются к любым ячейкам в этом диапазоне. |
getCell(row, column) | Range | Возвращает заданную ячейку в диапазоне. |
getColumn() | Integer | Возвращает начальную позицию столбца для этого диапазона. |
getDataRegion() | Range | Возвращает копию диапазона, расширенного по четырем основным Direction , чтобы покрыть все соседние ячейки с данными в них. |
getDataRegion(dimension) | Range | Возвращает копию расширенного диапазона Direction.UP и Direction.DOWN , если указанное измерение — Dimension.ROWS , или Direction.NEXT и Direction.PREVIOUS , если измерение — Dimension.COLUMNS . |
getDataSourceFormula() | DataSourceFormula | Возвращает DataSourceFormula для первой ячейки в диапазоне или null , если ячейка не содержит формулу источника данных. |
getDataSourceFormulas() | DataSourceFormula[] | Возвращает DataSourceFormula для ячеек в диапазоне. |
getDataSourcePivotTables() | DataSourcePivotTable[] | Получает все сводные таблицы источников данных, пересекающиеся с диапазоном. |
getDataSourceTables() | DataSourceTable[] | Получает все таблицы источников данных, пересекающиеся с диапазоном. |
getDataSourceUrl() | String | Возвращает URL-адрес данных в этом диапазоне, который можно использовать для создания диаграмм и запросов. |
getDataTable() | DataTable | Верните данные внутри этого объекта как DataTable. |
getDataTable(firstRowIsHeader) | DataTable | Верните данные внутри этого диапазона как DataTable. |
getDataValidation() | DataValidation | Возвращает правило проверки данных для верхней левой ячейки диапазона. |
getDataValidations() | DataValidation[][] | Возвращает правила проверки данных для всех ячеек в диапазоне. |
getDeveloperMetadata() | DeveloperMetadata[] | Получите метаданные разработчика, связанные с этим диапазоном. |
getDisplayValue() | String | Возвращает отображаемое значение верхней левой ячейки диапазона. |
getDisplayValues() | String[][] | Возвращает прямоугольную сетку значений для этого диапазона. |
getFilter() | Filter | Возвращает фильтр на листе, к которому принадлежит этот диапазон, или null если на листе нет фильтра. |
getFontColorObject() | Color | Возвращает цвет шрифта ячейки в верхнем левом углу диапазона. |
getFontColorObjects() | Color[][] | Возвращает цвета шрифта ячеек в диапазоне. |
getFontFamilies() | String[][] | Возвращает семейства шрифтов ячеек в диапазоне. |
getFontFamily() | String | Возвращает семейство шрифтов ячейки в верхнем левом углу диапазона. |
getFontLine() | String | Получает стиль линии ячейки в верхнем левом углу диапазона ( 'underline' , 'line-through' или 'none' ). |
getFontLines() | String[][] | Получает стиль линии ячеек в диапазоне ( 'underline' , 'line-through' или 'none' ). |
getFontSize() | Integer | Возвращает размер шрифта в пунктах ячейки в верхнем левом углу диапазона. |
getFontSizes() | Integer[][] | Возвращает размеры шрифта ячеек в диапазоне. |
getFontStyle() | String | Возвращает стиль шрифта ( 'italic' или 'normal' ) ячейки в верхнем левом углу диапазона. |
getFontStyles() | String[][] | Возвращает стили шрифтов ячеек в диапазоне. |
getFontWeight() | String | Возвращает толщину шрифта (обычный/полужирный) ячейки в верхнем левом углу диапазона. |
getFontWeights() | String[][] | Возвращает вес шрифта ячеек в диапазоне. |
getFormula() | String | Возвращает формулу (нотация A1) для верхней левой ячейки диапазона или пустую строку, если ячейка пуста или не содержит формулы. |
getFormulaR1C1() | String | Возвращает формулу (обозначение R1C1) для заданной ячейки или null , если нет. |
getFormulas() | String[][] | Возвращает формулы (нотация A1) для ячеек в диапазоне. |
getFormulasR1C1() | String[][] | Возвращает формулы (нотация R1C1) для ячеек в диапазоне. |
getGridId() | Integer | Возвращает идентификатор сетки родительского листа диапазона. |
getHeight() | Integer | Возвращает высоту диапазона. |
getHorizontalAlignment() | String | Возвращает горизонтальное выравнивание текста (слева/по центру/справа) ячейки в верхнем левом углу диапазона. |
getHorizontalAlignments() | String[][] | Возвращает горизонтальное выравнивание ячеек в диапазоне. |
getLastColumn() | Integer | Возвращает позицию конца столбца. |
getLastRow() | Integer | Возвращает позицию конца строки. |
getMergedRanges() | Range[] | Возвращает массив объектов Range , представляющих объединенные ячейки, которые либо полностью находятся в пределах текущего диапазона, либо содержат хотя бы одну ячейку в текущем диапазоне. |
getNextDataCell(direction) | Range | Начиная с ячейки в первом столбце и строке диапазона, возвращает следующую ячейку в заданном направлении, которая является краем непрерывного диапазона ячеек с данными в них или ячейкой на краю электронной таблицы в этом направлении. |
getNote() | String | Возвращает заметку, связанную с заданным диапазоном. |
getNotes() | String[][] | Возвращает примечания, связанные с ячейками в диапазоне. |
getNumColumns() | Integer | Возвращает количество столбцов в этом диапазоне. |
getNumRows() | Integer | Возвращает количество строк в этом диапазоне. |
getNumberFormat() | String | Получите формат числа или даты в верхней левой ячейке заданного диапазона. |
getNumberFormats() | String[][] | Возвращает числовой формат или формат даты для ячеек в диапазоне. |
getRichTextValue() | RichTextValue | Возвращает значение Rich Text для верхней левой ячейки диапазона или null , если значение ячейки не является текстом. |
getRichTextValues() | RichTextValue[][] | Возвращает значения форматированного текста для ячеек в диапазоне. |
getRow() | Integer | Возвращает позицию строки для этого диапазона. |
getRowIndex() | Integer | Возвращает позицию строки для этого диапазона. |
getSheet() | Sheet | Возвращает лист, которому принадлежит этот диапазон. |
getTextDirection() | TextDirection | Возвращает направление текста для верхней левой ячейки диапазона. |
getTextDirections() | TextDirection[][] | Возвращает направления текста для ячеек в диапазоне. |
getTextRotation() | TextRotation | Возвращает настройки поворота текста для верхней левой ячейки диапазона. |
getTextRotations() | TextRotation[][] | Возвращает настройки поворота текста для ячеек в диапазоне. |
getTextStyle() | TextStyle | Возвращает стиль текста для верхней левой ячейки диапазона. |
getTextStyles() | TextStyle[][] | Возвращает стили текста для ячеек в диапазоне. |
getValue() | Object | Возвращает значение верхней левой ячейки диапазона. |
getValues() | Object[][] | Возвращает прямоугольную сетку значений для этого диапазона. |
getVerticalAlignment() | String | Возвращает вертикальное выравнивание (сверху/посередине/снизу) ячейки в верхнем левом углу диапазона. |
getVerticalAlignments() | String[][] | Возвращает вертикальное выравнивание ячеек в диапазоне. |
getWidth() | Integer | Возвращает ширину диапазона в столбцах. |
getWrap() | Boolean | Возвращает, переносится ли текст в ячейке. |
getWrapStrategies() | WrapStrategy[][] | Возвращает стратегии переноса текста для ячеек в диапазоне. |
getWrapStrategy() | WrapStrategy | Возвращает стратегию переноса текста для верхней левой ячейки диапазона. |
getWraps() | Boolean[][] | Возвращает, переносится ли текст в ячейках. |
insertCells(shiftDimension) | Range | Вставляет пустые ячейки в этот диапазон. |
insertCheckboxes() | Range | Вставляет флажки в каждую ячейку в диапазоне, настроенном со true для отмеченного и false для неотмеченного. |
insertCheckboxes(checkedValue) | Range | Вставляет флажки в каждую ячейку в диапазоне, настроенном с пользовательским значением для отмеченных и пустой строкой для неотмеченных. |
insertCheckboxes(checkedValue, uncheckedValue) | Range | Вставляет флажки в каждую ячейку в диапазоне, настроенные с пользовательскими значениями для отмеченного и неотмеченного состояний. |
isBlank() | Boolean | Возвращает true , если диапазон полностью пуст. |
isChecked() | Boolean | Возвращает, все ли ячейки в диапазоне имеют состояние флажка как «отмечено». |
isEndColumnBounded() | Boolean | Определяет, привязан ли конец диапазона к определенному столбцу. |
isEndRowBounded() | Boolean | Определяет, привязан ли конец диапазона к определенной строке. |
isPartOfMerge() | Boolean | Возвращает true , если ячейки в текущем диапазоне перекрывают любые объединенные ячейки. |
isStartColumnBounded() | Boolean | Определяет, привязано ли начало диапазона к определенному столбцу. |
isStartRowBounded() | Boolean | Определяет, привязано ли начало диапазона к определенной строке. |
merge() | Range | Объединяет ячейки диапазона в один блок. |
mergeAcross() | Range | Объедините ячейки в диапазоне по столбцам диапазона. |
mergeVertically() | Range | Объединяет ячейки в диапазоне вместе. |
moveTo(target) | void | Вырежьте и вставьте (как формат, так и значения) из этого диапазона в целевой диапазон. |
offset(rowOffset, columnOffset) | Range | Возвращает новый диапазон, смещенный от этого диапазона на заданное количество строк и столбцов (которое может быть отрицательным). |
offset(rowOffset, columnOffset, numRows) | Range | Возвращает новый диапазон относительно текущего диапазона, верхняя левая точка которого смещена от текущего диапазона на заданные строки и столбцы и с заданной высотой в ячейках. |
offset(rowOffset, columnOffset, numRows, numColumns) | Range | Возвращает новый диапазон относительно текущего диапазона, верхняя левая точка которого смещена от текущего диапазона на заданные строки и столбцы, а также с заданной высотой и шириной в ячейках. |
protect() | Protection | Создает объект, который может защитить диапазон от редактирования, кроме пользователей, у которых есть разрешение. |
randomize() | Range | Рандомизирует порядок строк в заданном диапазоне. |
removeCheckboxes() | Range | Удаляет все флажки из диапазона. |
removeDuplicates() | Range | Удаляет строки в этом диапазоне, содержащие значения, дублирующие значения в любой предыдущей строке. |
removeDuplicates(columnsToCompare) | Range | Удаляет строки в пределах этого диапазона, которые содержат значения в указанных столбцах, которые являются дубликатами значений любой предыдущей строки. |
setBackground(color) | Range | Устанавливает цвет фона всех ячеек в диапазоне в нотации CSS (например, '#ffffff' или 'white' ). |
setBackgroundObject(color) | Range | Устанавливает цвет фона всех ячеек в диапазоне. |
setBackgroundObjects(color) | Range | Устанавливает прямоугольную сетку цветов фона (должна соответствовать размерам этого диапазона). |
setBackgroundRGB(red, green, blue) | Range | Задает заданный цвет фона с использованием значений RGB (целые числа от 0 до 255 включительно). |
setBackgrounds(color) | Range | Устанавливает прямоугольную сетку цветов фона (должна соответствовать размерам этого диапазона). |
setBorder(top, left, bottom, right, vertical, horizontal) | Range | Задает свойство границы. |
setBorder(top, left, bottom, right, vertical, horizontal, color, style) | Range | Задает свойство границы с цветом и/или стилем. |
setDataValidation(rule) | Range | Задает одно правило проверки данных для всех ячеек диапазона. |
setDataValidations(rules) | Range | Задает правила проверки данных для всех ячеек диапазона. |
setFontColor(color) | Range | Задает цвет шрифта в нотации CSS (например, '#ffffff' или 'white' ). |
setFontColorObject(color) | Range | Задает цвет шрифта заданного диапазона. |
setFontColorObjects(colors) | Range | Задает прямоугольную сетку цветов шрифта (должны соответствовать размерам этого диапазона). |
setFontColors(colors) | Range | Задает прямоугольную сетку цветов шрифта (должны соответствовать размерам этого диапазона). |
setFontFamilies(fontFamilies) | Range | Задает прямоугольную сетку семейств шрифтов (размеры должны соответствовать этому диапазону). |
setFontFamily(fontFamily) | Range | Задает семейство шрифтов, например «Arial» или «Helvetica». |
setFontLine(fontLine) | Range | Устанавливает стиль линии шрифта заданного диапазона ( 'underline' , 'line-through' или 'none' ). |
setFontLines(fontLines) | Range | Задает прямоугольную сетку стилей линий (размеры должны соответствовать этому диапазону). |
setFontSize(size) | Range | Устанавливает размер шрифта, при этом размер является используемым размером точек. |
setFontSizes(sizes) | Range | Задает прямоугольную сетку размеров шрифта (должны соответствовать размерам этого диапазона). |
setFontStyle(fontStyle) | Range | Установите стиль шрифта для заданного диапазона ( 'italic' или 'normal' ). |
setFontStyles(fontStyles) | Range | Задает прямоугольную сетку стилей шрифта (размеры должны соответствовать этому диапазону). |
setFontWeight(fontWeight) | Range | Установите толщину шрифта для заданного диапазона (обычный/жирный). |
setFontWeights(fontWeights) | Range | Устанавливает прямоугольную сетку жирности шрифта (должна соответствовать размерам этого диапазона). |
setFormula(formula) | Range | Обновляет формулу для этого диапазона. |
setFormulaR1C1(formula) | Range | Обновляет формулу для этого диапазона. |
setFormulas(formulas) | Range | Задает прямоугольную сетку формул (размеры должны соответствовать этому диапазону). |
setFormulasR1C1(formulas) | Range | Задает прямоугольную сетку формул (размеры должны соответствовать этому диапазону). |
setHorizontalAlignment(alignment) | Range | Установите горизонтальное (слева направо) выравнивание для заданного диапазона (слева/по центру/справа). |
setHorizontalAlignments(alignments) | Range | Задает прямоугольную сетку горизонтальных выравниваний. |
setNote(note) | Range | Устанавливает ноту на заданное значение. |
setNotes(notes) | Range | Устанавливает прямоугольную сетку заметок (должна соответствовать размерам этого диапазона). |
setNumberFormat(numberFormat) | Range | Устанавливает числовой формат или формат даты в заданную строку форматирования. |
setNumberFormats(numberFormats) | Range | Задает прямоугольную сетку форматов чисел или дат (должны соответствовать размерам этого диапазона). |
setRichTextValue(value) | Range | Задает значение форматированного текста для ячеек в диапазоне. |
setRichTextValues(values) | Range | Задает прямоугольную сетку значений форматированного текста. |
setShowHyperlink(showHyperlink) | Range | Устанавливает, должен ли диапазон показывать гиперссылки. |
setTextDirection(direction) | Range | Задает направление текста для ячеек в диапазоне. |
setTextDirections(directions) | Range | Задает прямоугольную сетку направлений текста. |
setTextRotation(degrees) | Range | Задает параметры поворота текста для ячеек в диапазоне. |
setTextRotation(rotation) | Range | Задает параметры поворота текста для ячеек в диапазоне. |
setTextRotations(rotations) | Range | Задает прямоугольную сетку поворотов текста. |
setTextStyle(style) | Range | Задает стиль текста для ячеек в диапазоне. |
setTextStyles(styles) | Range | Задает прямоугольную сетку стилей текста. |
setValue(value) | Range | Устанавливает значение диапазона. |
setValues(values) | Range | Задает прямоугольную сетку значений (должны соответствовать размерам этого диапазона). |
setVerticalAlignment(alignment) | Range | Установите вертикальное (сверху вниз) выравнивание для заданного диапазона (сверху/посередине/снизу). |
setVerticalAlignments(alignments) | Range | Задает прямоугольную сетку выравнивания по вертикали (размеры должны соответствовать этому диапазону). |
setVerticalText(isVertical) | Range | Устанавливает, следует ли складывать текст для ячеек в диапазоне. |
setWrap(isWrapEnabled) | Range | Установить перенос ячейки заданного диапазона. |
setWrapStrategies(strategies) | Range | Задает прямоугольную сетку стратегий переноса. |
setWrapStrategy(strategy) | Range | Задает стратегию переноса текста для ячеек в диапазоне. |
setWraps(isWrapEnabled) | Range | Задает прямоугольную сетку политик переноса слов (размеры должны соответствовать этому диапазону). |
shiftColumnGroupDepth(delta) | Range | Изменяет глубину группировки столбцов диапазона на указанную величину. |
shiftRowGroupDepth(delta) | Range | Изменяет глубину группировки строк диапазона на указанную величину. |
sort(sortSpecObj) | Range | Сортирует ячейки в заданном диапазоне по столбцу и указанному порядку. |
splitTextToColumns() | void | Разбивает столбец текста на несколько столбцов на основе автоматически определяемого разделителя. |
splitTextToColumns(delimiter) | void | Разделяет столбец текста на несколько столбцов, используя указанную строку в качестве пользовательского разделителя. |
splitTextToColumns(delimiter) | void | Разбивает столбец текста на несколько столбцов на основе указанного разделителя. |
trimWhitespace() | Range | Обрезает пробелы (например, пробелы, символы табуляции или новые строки) в каждой ячейке в этом диапазоне. |
uncheck() | Range | Изменяет состояние флажков в диапазоне на «не отмечен». |
Подробная документация
activate()
Устанавливает указанный диапазон в качестве active range
, при этом верхняя левая ячейка в диапазоне является current cell
.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var range = sheet.getRange('A1:D10'); range.activate(); var selection = sheet.getSelection(); // Current cell: A1 var currentCell = selection.getCurrentCell(); // Active Range: A1:D10 var activeRange = selection.getActiveRange();
Возвращаться
Range
— этот диапазон для цепочки.
activateAsCurrentCell()
Устанавливает указанную ячейку в качестве current cell
.
Если указанная ячейка присутствует в существующем диапазоне, то этот диапазон становится активным диапазоном с ячейкой в качестве текущей ячейки.
Если указанная ячейка не присутствует ни в одном из существующих диапазонов, существующий выбор удаляется, и ячейка становится текущей ячейкой и активным диапазоном.
Примечание. Указанный Range
должен состоять из одной ячейки, иначе будет выдано исключение.
// Gets the first sheet of the spreadsheet. var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; // Gets the cell B5 and sets it as the active cell. var range = sheet.getRange('B5'); var 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
addDeveloperMetadata(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
addDeveloperMetadata(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 | DeveloperMetadataVisibility | Видимость новых метаданных разработчика. |
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addDeveloperMetadata(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 on the sheet. 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
addDeveloperMetadata(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 | DeveloperMetadataVisibility | Видимость новых метаданных разработчика. |
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
applyColumnBanding()
Применяет тему чередования столбцов по умолчанию к диапазону. По умолчанию полоса имеет цвет заголовка и не имеет цвета нижнего колонтитула.
// 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
applyColumnBanding(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());
Параметры
Имя | Тип | Описание |
---|---|---|
bandingTheme | BandingTheme | Цветовая тема для применения к столбцам в диапазоне. |
Возвращаться
Banding
— новый бэндинг.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
applyColumnBanding(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());
Параметры
Имя | Тип | Описание |
---|---|---|
bandingTheme | BandingTheme | Цветовая тема для применения к столбцам в диапазоне. |
showHeader | Boolean | Если true , цвет заголовка темы полос применяется к первому столбцу. |
showFooter | Boolean | Если true , цвет нижнего колонтитула темы полос применяется к последнему столбцу. |
Возвращаться
Banding
— новый бэндинг.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
applyRowBanding()
Применяет тему объединения строк по умолчанию к диапазону. По умолчанию полоса имеет цвет заголовка и не имеет цвета нижнего колонтитула.
Возвращаться
Banding
— новый бэндинг.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
applyRowBanding(bandingTheme)
Применяет указанную тему объединения строк к диапазону. По умолчанию полоса имеет цвет заголовка и не имеет цвета нижнего колонтитула.
Параметры
Имя | Тип | Описание |
---|---|---|
bandingTheme | BandingTheme | Цветовая тема, применяемая к строкам в диапазоне. |
Возвращаться
Banding
— новый бэндинг.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
applyRowBanding(bandingTheme, showHeader, showFooter)
Применяет указанную тему чередования строк к диапазону с указанными настройками верхнего и нижнего колонтитула.
Параметры
Имя | Тип | Описание |
---|---|---|
bandingTheme | BandingTheme | Цветовая тема, применяемая к строкам в диапазоне. |
showHeader | Boolean | Если true , цвет заголовка темы полос применяется к первой строке. |
showFooter | Boolean | Если true , цвет нижнего колонтитула темы полос применяется к последней строке. |
Возвращаться
Banding
— новый бэндинг.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
autoFill(destination, series)
Заполняет destinationRange
данными на основе данных в этом диапазоне. Новые значения также определяются указанным типом series
. Целевой диапазон должен содержать этот диапазон и расширяться только в одном направлении. Например, следующий код заполняет A1:A20
рядом возрастающих чисел на основе текущих значений в A1:A4
:
var sheet = SpreadsheetApp.getActiveSheet(); // Has values [1, 2, 3, 4]. var sourceRange = sheet.getRange("A1:A4"); // The range to fill with values. var 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 | AutoFillSeries | Тип ряда автозаполнения, который следует использовать для вычисления новых значений. Эффект этой серии различается в зависимости от типа и количества исходных данных. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
autoFillToNeighbor(series)
Вычисляет диапазон для заполнения новыми данными на основе соседних ячеек и автоматически заполняет этот диапазон новыми значениями на основе данных, содержащихся в этом диапазоне. Эти новые значения также определяются указанным типом series
.
Вычисленный целевой диапазон учитывает окружающие данные, чтобы определить, куда должны быть вставлены новые значения: если есть данные непосредственно слева или справа от столбца, который заполняется автоматически, новые значения распространяются только до этих смежных данных.
Например, если A1:A20
заполнен рядом возрастающих чисел и этот метод вызывается для диапазона B1:B4
, который содержит ряд дат, новые значения вставляются только в B5:B20
. Таким образом, эти новые значения «прилипают» к ячейкам, содержащим значения в столбце A.
var sheet = SpreadsheetApp.getActiveSheet(); // A1:A20 has values [1, 2, 3, ... 20]. // B1:B4 has values [1/1/2017, 1/2/2017, ...] var sourceRange = sheet.getRange("B1:B4"); // Results in B5:B20 having values [1/5/2017, ... 1/20/2017] sourceRange.autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
Параметры
Имя | Тип | Описание |
---|---|---|
series | AutoFillSeries | Тип ряда автозаполнения, который следует использовать для вычисления новых значений. Эффект этой серии различается в зависимости от типа и количества исходных данных. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
breakApart()
Снова разбейте все ячейки с несколькими столбцами в диапазоне на отдельные ячейки.
Вызов этой функции для диапазона эквивалентен выбору диапазона и щелчку по Формату -> Объединить -> Разъединить.
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
canEdit()
Определяет, есть ли у пользователя разрешение на редактирование каждой ячейки в диапазоне. Владелец электронной таблицы всегда может редактировать защищенные диапазоны и листы.
Возвращаться
Boolean
— true
, если у пользователя есть разрешение на редактирование каждой ячейки в диапазоне; 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'. var range = SpreadsheetApp.getActive().getRange('A1:B10'); range.check();
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
clear()
Очищает диапазон содержимого и форматов.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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:G8 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, задающий расширенные параметры, перечисленные ниже. |
Расширенные параметры
Имя | Тип | Описание |
---|---|---|
commentsOnly | Boolean | Очистить только комментарии. |
contentsOnly | Boolean | Очистить только содержимое. |
formatOnly | Boolean | Очистить ли только формат; обратите внимание, что формат очистки также очищает правила проверки данных. |
validationsOnly | Boolean | Очистить только правила проверки данных. |
skipFilteredRows | Boolean | Следует ли избегать очистки отфильтрованных строк. |
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
clearContent()
Очищает содержимое диапазона, оставляя форматирование нетронутым.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D10"); range.clearContent();
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
clearDataValidations()
Очищает правила проверки данных для диапазона.
// Clear the data validation rules for cells A1:B5. var range = SpreadsheetApp.getActive().getRange('A1:B5'); range.clearDataValidations();
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
clearFormat()
Очищает форматирование для этого диапазона.
Это очищает форматирование текста для ячейки или ячеек в диапазоне, но не сбрасывает правила форматирования чисел.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D10"); range.clearFormat();
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
clearNote()
Очищает заметку в указанной ячейке или ячейках.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D10"); range.clearNote();
Возвращаться
Range
— этот диапазон для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
collapseGroups()
Сворачивает все группы, которые полностью входят в диапазон. Если ни одна группа не находится полностью в пределах диапазона, самая глубокая развернутая группа, которая частично находится в пределах диапазона, сворачивается.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var 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
copyFormatToRange(gridId, column, columnEnd, row, rowEnd)
Скопируйте форматирование диапазона в указанное место. Если место назначения больше или меньше исходного диапазона, то источник соответственно повторяется или усекается. Обратите внимание, что этот метод копирует только форматирование.
Подробное описание параметра gridId см. в разделе getGridId()
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var source = ss.getSheets()[0]; var 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);
Параметры
Имя | Тип | Описание |
---|---|---|
gridId | Integer | Уникальный идентификатор листа в электронной таблице, независимо от его положения. |
column | Integer | Первый столбец целевого диапазона. |
columnEnd | Integer | Конечный столбец целевого диапазона. |
row | Integer | Начальная строка целевого диапазона. |
rowEnd | Integer | Конечная строка целевого диапазона. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
Смотрите также
copyFormatToRange(sheet, column, columnEnd, row, rowEnd)
Скопируйте форматирование диапазона в указанное место. Если место назначения больше или меньше исходного диапазона, то источник соответственно повторяется или усекается. Обратите внимание, что этот метод копирует только форматирование.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var source = ss.getSheets()[0]; var destination = ss.getSheets()[1]; var 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 | Первый столбец целевого диапазона. |
columnEnd | Integer | Конечный столбец целевого диапазона. |
row | Integer | Начальная строка целевого диапазона. |
rowEnd | Integer | Конечная строка целевого диапазона. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
copyTo(destination)
Копирует данные из диапазона ячеек в другой диапазон ячеек. Копируются как значения, так и форматирование.
// The code below copies the first 5 columns over to the 6th column. var sheet = SpreadsheetApp.getActiveSheet(); var 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
copyTo(destination, copyPasteType, transposed)
Копирует данные из диапазона ячеек в другой диапазон ячеек.
// The code below copies only the values of the first 5 columns over to the 6th column. var sheet = SpreadsheetApp.getActiveSheet(); sheet.getRange("A:E").copyTo(sheet.getRange("F1"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
Параметры
Имя | Тип | Описание |
---|---|---|
destination | Range | Целевой диапазон для копирования; важна только верхняя левая позиция ячейки. |
copyPasteType | CopyPasteType | Тип, указывающий, как содержимое диапазона вставляется в место назначения. |
transposed | Boolean | Должен ли диапазон вставляться в транспонированной ориентации. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
copyTo(destination, options)
Копирует данные из диапазона ячеек в другой диапазон ячеек. По умолчанию копируются и значения, и форматирование, но это можно переопределить с помощью расширенных аргументов.
// The code below copies only the values of the first 5 columns over to the 6th column. var sheet = SpreadsheetApp.getActiveSheet(); sheet.getRange("A:E").copyTo(sheet.getRange("F1"), {contentsOnly:true});
Параметры
Имя | Тип | Описание |
---|---|---|
destination | Range | Целевой диапазон для копирования; важна только верхняя левая позиция ячейки. |
options | Object | Объект JavaScript, задающий расширенные параметры, перечисленные ниже. |
Расширенные параметры
Имя | Тип | Описание |
---|---|---|
formatOnly | Boolean | указывает, что следует копировать только формат |
contentsOnly | Boolean | указывает, что копировать следует только содержимое |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
copyValuesToRange(gridId, column, columnEnd, row, rowEnd)
Скопируйте содержимое диапазона в указанное место. Если место назначения больше или меньше исходного диапазона, то источник соответственно повторяется или усекается.
Подробное описание параметра gridId см. в разделе getGridId()
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var source = ss.getSheets()[0]; var 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);
Параметры
Имя | Тип | Описание |
---|---|---|
gridId | Integer | Уникальный идентификатор листа в электронной таблице, независимо от его положения. |
column | Integer | Первый столбец целевого диапазона. |
columnEnd | Integer | Конечный столбец целевого диапазона. |
row | Integer | Начальная строка целевого диапазона. |
rowEnd | Integer | Конечная строка целевого диапазона. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
Смотрите также
copyValuesToRange(sheet, column, columnEnd, row, rowEnd)
Скопируйте содержимое диапазона в указанное место. Если место назначения больше или меньше исходного диапазона, то источник соответственно повторяется или усекается.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var source = ss.getSheets()[0]; var destination = ss.getSheets()[1]; var 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 | Первый столбец целевого диапазона. |
columnEnd | Integer | Конечный столбец целевого диапазона. |
row | Integer | Начальная строка целевого диапазона. |
rowEnd | Integer | Конечная строка целевого диапазона. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createDataSourcePivotTable(dataSource)
Создает пустую сводную таблицу источника данных из источника данных, привязанную к первой ячейке в этом диапазоне.
В этом примере показано, как создать и настроить новую сводную таблицу источника данных.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var anchorCell = spreadsheet.getSheets()[0].getRange('A1'); var dataSource = spreadsheet.getDataSources()[0]; var pivotTable = anchorCell.createDataSourcePivotTable(dataSource); pivotTable.addRowGroup('dataColumnA'); pivotTable.addColumnGroup('dataColumnB'); pivotTable.addPivotValue('dataColumnC', SpreadsheetApp.PivotTableSummarizeFunction.SUM); pivotTable.addFilter('dataColumnA', SpreadsheetApp.newFilterCriteria().whenTextStartsWith('A').build());
Параметры
Имя | Тип | Описание |
---|---|---|
dataSource | DataSource | Источник данных для создания сводной таблицы. |
Возвращаться
DataSourcePivotTable
— только что созданная сводная таблица источника данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createDataSourceTable(dataSource)
Создает пустую таблицу источника данных из источника данных, привязанную к первой ячейке в этом диапазоне.
В этом примере показано, как создать и настроить новую таблицу источника данных.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var anchorCell = spreadsheet.getSheets()[0].getRange('A1'); var dataSource = spreadsheet.getDataSources()[0]; var dataSourceTable = anchorCell.createDataSourceTable(dataSource); .addColumns('dataColumnA', 'dataColumnB', 'dataColumnC') .addSortSpec('dataColumnA', /* ascending= *\/ true) .addSortSpec('dataColumnB', /* ascending= *\/ false);
Параметры
Имя | Тип | Описание |
---|---|---|
dataSource | DataSource | Источник данных для создания сводной таблицы. |
Возвращаться
DataSourceTable
— только что созданная таблица источника данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createDeveloperMetadataFinder()
Возвращает 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());
Возвращаться
DeveloperMetadataFinder
— средство поиска метаданных разработчика для поиска метаданных в рамках этого диапазона.
createFilter()
Создает фильтр и применяет его к указанному диапазону на листе. Вы не можете создать более одного фильтра на листе. Чтобы получить доступ и изменить свой фильтр после его создания, используйте getFilter()
или Sheet.getFilter()
.
let ss = SpreadsheetApp.getActiveSheet(); let 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() { let filter = range.getFilter(); let criteria = SpreadsheetApp.newFilterCriteria() .whenCellNotEmpty() .build(); filter.setColumnFilterCriteria(2, criteria); }Используйте этот метод для создания фильтров для листов
Grid
, типа листа по умолчанию. Листы сетки — это листы, не подключенные к базе данных. Для создания других типов фильтров см.:- Создайте фильтр сводной таблицы с помощью
PivotTable.addFilter(sourceDataColumn, filterCriteria)
- Создайте фильтр для листа, подключенного к базе данных, с помощью
DataSourceSheet.addFilter(columnName, filterCriteria)
- Создайте фильтр для сводной таблицы, подключенной к базе данных с помощью
DataSourcePivotTable.addFilter(columnName, filterCriteria)
Возвращаться
Filter
— новый фильтр.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createPivotTable(sourceData)
Создает пустую сводную таблицу из указанных sourceData
, привязанных к первой ячейке в этом диапазоне.
// 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());
Параметры
Имя | Тип | Описание |
---|---|---|
sourceData | Range | Данные для создания сводной таблицы. |
Возвращаться
PivotTable
— только что созданная PivotTable
.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createTextFinder(findText)
Создает средство поиска текста для диапазона, которое может найти и заменить текст в этом диапазоне.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var range = sheet.getActiveRange(); // Creates a text finder for the range. var textFinder = range.createTextFinder('dog'); // Returns the first occurrence of 'dog'. var firstOccurrence = textFinder.findNext(); // Replaces the last found occurrence of 'dog' with 'cat' and returns the number // of occurrences replaced. var numOccurrencesReplaced = findOccurrence.replaceWith('cat');
Параметры
Имя | Тип | Описание |
---|---|---|
findText | String | Текст для поиска. |
Возвращаться
TextFinder
— TextFinder
для диапазона
deleteCells(shiftDimension)
Удаляет этот диапазон ячеек. Существующие данные на листе по предоставленному измерению смещаются в сторону удаленного диапазона.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D10"); range.deleteCells(SpreadsheetApp.Dimension.COLUMNS);
Параметры
Имя | Тип | Описание |
---|---|---|
shiftDimension | Dimension | Измерение, по которому следует сместить существующие данные. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
expandGroups()
Разворачивает свернутые группы, диапазон которых или переключатель управления пересекаются с этим диапазоном. Расположение переключателя управления — это индекс, в котором отображается переключатель управления, непосредственно перед или после группы в зависимости от настроек. Если в одном и том же месте находится более одной группы, расширяется самая мелкая группа.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var 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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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
getBackground()
Возвращает цвет фона верхней левой ячейки в диапазоне (например, '#ffffff'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B5"); Logger.log(cell.getBackground());
Возвращаться
String
— Цветовой код фона.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getBackgroundObject()
Возвращает цвет фона верхней левой ячейки диапазона.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B5"); Logger.log(cell.getBackgroundObject().asRgbColor().asHexString());
Возвращаться
Color
— цвет фона верхней левой ячейки диапазона.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getBackgroundObjects()
Возвращает цвета фона ячеек в диапазоне.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5:C6"); var bgColors = range.getBackgroundObjects(); for (var i in bgColors) { for (var j in bgColors[i]) { Logger.log(bgColors[i][j].asRgbColor().asHexString()); } }
Возвращаться
Color[][]
— двумерный массив фоновых цветов.
Авторизация
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
getBackgrounds()
Returns the background colors of the cells in the range (for example, '#ffffff'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5:C6"); var bgColors = range.getBackgrounds(); for (var i in bgColors) { for (var j in bgColors[i]) { Logger.log(bgColors[i][j]); } }
Return
String[][]
— A two-dimensional array of color codes of the backgrounds.
Authorization
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
getBandings()
Returns all the bandings that are applied to any cells in this range.
// 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 (let banding of bandings) { console.log(banding.getSecondRowColor()); }
Return
Banding[]
— All the bandings that are applied to any cells in this range.
Authorization
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
getCell(row, column)
Returns a given cell within a range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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 var cell = range.getCell(1, 1); Logger.log(cell.getValue());
Parameters
Name | Type | Описание |
---|---|---|
row | Integer | The row of the cell relative to the range. |
column | Integer | The column of the cell relative to the range. |
Return
Range
— A range containing a single cell at the specified coordinates.
Authorization
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
getColumn()
Returns the starting column position for this range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); // Logs "2.0" Logger.log(range.getColumn());
Return
Integer
— The range's starting column position in the spreadsheet.
Authorization
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
getDataRegion()
Returns a copy of the range expanded in the four cardinal Direction
s to cover all adjacent cells with data in them. If the range is surrounded by empty cells not including those along the diagonals, the range itself is returned. This is similar to selecting the range and typing Ctrl+A
in the editor.
// Assume the active spreadsheet is blank. var ss = SpreadsheetApp.getActiveSpreadsheet(); var 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());
Return
Range
— The range's data region or a range for the entire spreadsheet.
Authorization
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
getDataRegion(dimension)
Returns a copy of the range expanded Direction.UP
and Direction.DOWN
if the specified dimension is Dimension.ROWS
, or Direction.NEXT
and Direction.PREVIOUS
if the dimension is Dimension.COLUMNS
. The expansion of the range is based on detecting data next to the range that is organized like a table. The expanded range covers all adjacent cells with data in them along the specified dimension including the table boundaries. If the original range is surrounded by empty cells along the specified dimension, the range itself is returned. This method is similar to selecting the range and typing Ctrl+Space
for columns or Shift+Space
for rows in the editor.
// Assume the active spreadsheet is blank. var ss = SpreadsheetApp.getActiveSpreadsheet(); var 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());
Parameters
Name | Type | Описание |
---|---|---|
dimension | Dimension | The dimension along which to expand the range. |
Return
Range
— The range's data region or a range covering each column or each row spanned by the original range.
Authorization
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
getDataSourceFormula()
Returns the DataSourceFormula
for the first cell in the range, or null
if the cell doesn't contain a data source formula.
Return
DataSourceFormula
— The DataSourceFormula
for the cell.
Authorization
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
getDataSourceFormulas()
Returns the DataSourceFormula
s for the cells in the range.
Return
DataSourceFormula[]
— An array of DataSourceFormula
s.
Authorization
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
getDataSourcePivotTables()
Gets all the data source pivot tables intersecting with the range.
Return
DataSourcePivotTable[]
— A list of data source pivot tables.
Authorization
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
getDataSourceTables()
Gets all the data source tables intersecting with the range.
Return
DataSourceTable[]
— A list of data source tables.
Authorization
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
getDataSourceUrl()
Returns a URL for the data in this range, which can be used to create charts and queries.
Code.gs
function doGet() { var ss = SpreadsheetApp.openById('1khO6hBWTNNyvyyxvob7aoZTI9ZvlqqASNeq0e29Tw2c'); var sheet = ss.getSheetByName('ContinentData'); var range = sheet.getRange('A1:B8'); var 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>
Return
String
— A URL for this range as a data source that can be passed to other APIs such as charts.
Authorization
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
getDataTable()
getDataTable(firstRowIsHeader)
Return the data inside this range as a DataTable.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:B7"); // Calling this method with "true" sets the first line to be the title of the axes var 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. var chart = Charts.newBarChart() .setDataTable(datatable) .setOption("title", "Your Title Here") .build();
Parameters
Name | Type | Описание |
---|---|---|
firstRowIsHeader | Boolean | Whether to treat the first row as a header. |
Return
DataTable
— The data as a datatable.
Authorization
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
getDataValidation()
Returns the data validation rule for the top-left cell in the range. If data validation has not been set on the cell, this method returns null
.
// Log information about the data validation rule for cell A1. var cell = SpreadsheetApp.getActive().getRange('A1'); var rule = cell.getDataValidation(); if (rule != null) { var criteria = rule.getCriteriaType(); var 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.') }
Return
DataValidation
— The data validation rule for the top-left cell in the range.
Authorization
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
getDataValidations()
Returns the data validation rules for all cells in the range. If data validation has not been set on a given cell, this method returns null
for that cell's position in the array.
// Change existing data validation rules that require a date in 2013 to require a date in 2014. var oldDates = [new Date('1/1/2013'), new Date('12/31/2013')]; var newDates = [new Date('1/1/2014'), new Date('12/31/2014')]; var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()); var rules = range.getDataValidations(); for (var i = 0; i < rules.length; i++) { for (var j = 0; j < rules[i].length; j++) { var rule = rules[i][j]; if (rule != null) { var criteria = rule.getCriteriaType(); var 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);
Return
DataValidation[][]
— A two-dimensional array of data validation rules associated with the cells in the range.
Authorization
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
getDeveloperMetadata()
Get the developer metadata associated with this range.
Return
DeveloperMetadata[]
— The developer metadata associated with this range.
Authorization
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
getDisplayValue()
Returns the displayed value of the top-left cell in the range. The value is a String
. The displayed value takes into account date, time and currency formatting formatting, including formats applied automatically by the spreadsheet's locale setting. Empty cells return an empty string.
Return
String
— The displayed value in this cell.
Authorization
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
getDisplayValues()
Returns the rectangular grid of values for this range.
Returns a two-dimensional array of displayed values, indexed by row, then by column. The values are String
objects. The displayed value takes into account date, time and currency formatting, including formats applied automatically by the spreadsheet's locale setting. 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 displayed values for the range C2:G8 // in the active spreadsheet. Note that this is a JavaScript array. var values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getDisplayValues(); Logger.log(values[0][0]);
Return
String[][]
— A two-dimensional array of values.
Authorization
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
getFilter()
Returns the filter on the sheet this range belongs to, or null
if there is no filter on the sheet.
let ss = SpreadsheetApp.getActiveSheet(); let range = ss.getRange("A1:C20"); // Gets the existing filter on the sheet that the given range belongs to. let filter = range.getFilter();
Return
Filter
— The filter.
Authorization
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
getFontColorObject()
Returns the font color of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontColorObject().asRgbColor().asHexString());
Return
Color
— The font color of the top-left cell in the range.
Authorization
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
getFontColorObjects()
Returns the font colors of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontColorObjects(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j].asRgbColor().asHexString()); } }
Return
Color[][]
— A two-dimensional array of font colors associated with cells in the range.
Authorization
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
getFontFamilies()
Returns the font families of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontFamilies(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of font families associated with cells in the range.
Authorization
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
getFontFamily()
Returns the font family of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontFamily());
Return
String
— The font family of the cell.
Authorization
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
getFontLine()
Gets the line style of the cell in the top-left corner of the range ( 'underline'
, 'line-through'
, or 'none'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontLine());
Return
String
— The font line.
Authorization
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
getFontLines()
Gets the line style of the cells in the range ( 'underline'
, 'line-through'
, or 'none'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontLines(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of font lines associated with cells in the range.
Authorization
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
getFontSize()
Returns the font size in point size of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontSize());
Return
Integer
— The font size in point size.
Authorization
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
getFontSizes()
Returns the font sizes of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontSizes(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
Integer[][]
— A two-dimensional array of font sizes of text associated with cells in the range.
Authorization
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
getFontStyle()
Returns the font style ( 'italic'
or 'normal'
) of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontStyle());
Return
String
— The font style of the text in the cell.
Authorization
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
getFontStyles()
Returns the font styles of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontStyles(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of font styles of text associated with cells in the range.
Authorization
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
getFontWeight()
Returns the font weight (normal/bold) of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getFontWeight());
Return
String
— The font weight of the text in the cell.
Authorization
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
getFontWeights()
Returns the font weights of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getFontWeights(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of font weights of text associated with cells in the range.
Authorization
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
getFormula()
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This assumes you have a function in B5 that sums up // B2:B4 var range = sheet.getRange("B5"); // Logs the calculated value and the formula Logger.log("Calculated value: %s Formula: %s", range.getValue(), range.getFormula());
Return
String
— The formula for the cell.
Authorization
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
getFormulaR1C1()
Returns the formula (R1C1 notation) for a given cell, or null
if none.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5"); var formula = range.getFormulaR1C1(); Logger.log(formula);
Return
String
— The formula in R1C1 notation.
Authorization
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
getFormulas()
Returns the formulas (A1 notation) for the cells in the range. Entries in the 2D array are empty strings for cells with no formula.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5:C6"); var formulas = range.getFormulas(); for (var i in formulas) { for (var j in formulas[i]) { Logger.log(formulas[i][j]); } }
Return
String[][]
— A two-dimensional array of formulas in string format.
Authorization
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
getFormulasR1C1()
Returns the formulas (R1C1 notation) for the cells in the range. Entries in the 2D array are null
for cells with no formula.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5:C6"); var formulas = range.getFormulasR1C1(); for (var i in formulas) { for (var j in formulas[i]) { Logger.log(formulas[i][j]); } }
Return
String[][]
— A two-dimensional array of formulas in R1C1 notation.
Authorization
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
getGridId()
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. var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getGridId());
Return
Integer
— The grid ID of the parent sheet.
Authorization
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
getHeight()
Returns the height of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); // logs 3.0 Logger.log(range.getHeight());
Return
Integer
— The height of the range.
Authorization
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
getHorizontalAlignment()
Returns the horizontal alignment of the text (left/center/right) of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getHorizontalAlignment());
Return
String
— The horizontal alignment of the text in the cell.
Authorization
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
getHorizontalAlignments()
Returns the horizontal alignments of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getHorizontalAlignments(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of horizontal alignments of text associated with cells in the range.
Authorization
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
getLastColumn()
Returns the end column position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); // Logs "4.0" Logger.log(range.getLastColumn());
Return
Integer
— The range's ending column position in the spreadsheet.
Authorization
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
getLastRow()
Returns the end row position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); // Logs "4.0" Logger.log(range.getLastRow());
Return
Integer
— The range's ending row position in the spreadsheet.
Authorization
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
getMergedRanges()
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:B3"); var mergedRanges = range.getMergedRanges(); for (var i = 0; i < mergedRanges.length; i++) { Logger.log(mergedRanges[i].getA1Notation()); Logger.log(mergedRanges[i].getDisplayValue()); }
Return
Range[]
— An array of Range
objects, representing merged cells overlapping the range.
getNextDataCell(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. var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("C3:E5"); // Logs "C1" Logger.log(range.getNextDataCell(SpreadsheetApp.Direction.UP).getA1Notation());
Parameters
Name | Type | Описание |
---|---|---|
direction | Direction | The direction in which to find the next data region edge cell. |
Return
Range
— The data region edge cell or the cell at the edge of the spreadsheet.
Authorization
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
getNote()
Returns the note associated with the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getNote());
Return
String
— The note associated with the given cell.
Authorization
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
getNotes()
Returns the notes associated with the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getNotes(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of notes associated with cells in the range.
Authorization
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
getNumColumns()
Returns the number of columns in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D5"); Logger.log(range.getNumColumns());
Return
Integer
— The number of columns in this range.
Authorization
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
getNumRows()
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D5"); Logger.log(range.getNumRows());
Return
Integer
— The number of rows in this range.
Authorization
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
getNumberFormat()
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 .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("C4"); Logger.log(cell.getNumberFormat());
Return
String
— The number format of the top-left cell of the range.
Authorization
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
getNumberFormats()
Returns the number or date formats for the cells in the range. The returned format patterns are described in the Sheets API documentation .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B5:C6"); var formats = range.getNumberFormats(); for (var i in formats) { for (var j in formats[i]) { Logger.log(formats[i][j]); } }
Return
String[][]
— A two-dimensional array of number formats.
Authorization
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
getRichTextValue()
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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("D4:F6"); var richText = range.getRichTextValue(); console.log(richText.getText());
Return
RichTextValue
— The Rich Text value of the top left cell in the range, or null
if the cell value is not text.
Authorization
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
getRichTextValues()
Returns the Rich Text values for the cells in the range.
// Gets the Rich Text values for all cells in range B5:C6 var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B5:C6"); var values = range.getRichTextValues(); for (var i = 0; i < values.length; i++) { for (var j = 0; j < values[i].length; j++) { console.log(values[i][j].getText()); } }
Return
RichTextValue[][]
— A two-dimensional array of Rich Text values.
Authorization
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
getRow()
Returns the row position for this range. Identical to getRowIndex() .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2"); Logger.log(range.getRow());
Return
Integer
— The row position of the range.
Authorization
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
getRowIndex()
Returns the row position for this range. Identical to getRow() .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2"); Logger.log(range.getRowIndex());
Return
Integer
— The row position of the range.
Authorization
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
See also
getSheet()
Returns the sheet this range belongs to.
Return
Sheet
— The sheet that this range belongs to.
Authorization
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
getTextDirection()
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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B1:D4"); Logger.log(range.getTextDirection());
Return
TextDirection
— The text direction of the top left cell in the range.
Authorization
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
getTextDirections()
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 var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B5:C6"); var directions = range.getTextDirections(); for (var i = 0; i < directions.length; i++) { for (var j = 0; j < directions[i].length; j++) { Logger.log(directions[i][j]); } }
Return
TextDirection[][]
— A two-dimensional array of text directions.
Authorization
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
getTextRotation()
Returns the text rotation settings for the top left cell of the range.
// Log the text rotation settings for a cell. var sheet = SpreadsheetApp.getActiveSheet(); var cell = sheet.getRange("A1"); Logger.log(cell.getTextRotation());
Return
TextRotation
— The text rotation settings.
Authorization
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
getTextRotations()
Returns the text rotation settings for the cells in the range.
var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B2:D4"); var results = range.getTextRotations(); for (var i in results) { for (var j in results[i]) { var rotation = results[i][j]; Logger.log("Cell [%s, %s] has text rotation: %v", i, j, rotation); } }
Return
TextRotation[][]
— A two-dimensional array of text rotations associated with cells in the range.
Authorization
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
getTextStyle()
Returns the text style for the top left cell of the range.
// Get the text style of cell D4. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("D4:F6"); var style = range.getTextStyle(); Logger.log(style);
Return
TextStyle
— The text style of the top left cell in the range.
Authorization
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
getTextStyles()
Returns the text styles for the cells in the range.
// Get the text styles for all cells in range B5:C6 var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B5:C6"); var styles = range.getTextStyles(); for (var i = 0; i < styles.length; i++) { for (var j = 0; j < styles[i].length; j++) { Logger.log(styles[i][j]); } }
Return
TextStyle[][]
— A two-dimensional array of text styles.
Authorization
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
getValue()
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.
Return
Object
— The value in this cell.
Authorization
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
getValues()
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. var 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. getValues()
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
.Return
Object[][]
— A two-dimensional array of values.
Authorization
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
getVerticalAlignment()
Returns the vertical alignment (top/middle/bottom) of the cell in the top-left corner of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getVerticalAlignment());
Return
String
— The vertical alignment of the text in the cell.
Authorization
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
getVerticalAlignments()
Returns the vertical alignments of the cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getVerticalAlignments(); for (var i in results) { for (var j in results[i]) { Logger.log(results[i][j]); } }
Return
String[][]
— A two-dimensional array of vertical alignments of text associated with cells in the range.
Authorization
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
getWidth()
Returns the width of the range in columns.
Return
Integer
— The number of columns in the range.
Authorization
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
getWrap()
Returns whether the text in the cell wraps. To get more granular wrap strategy, use getWrapStrategy()
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getWrap());
Return
Boolean
— Whether the text in this cell wraps or not.
Authorization
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
getWrapStrategies()
Returns the text wrapping strategies for the cells in the range.
// Get the text wrapping strategies for all cells in range B5:C6 var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B5:C6"); var strategies = range.getWrapStrategies(); for (var i = 0; i < strategies.length; i++) { for (var j = 0; j < strategies[i].length; j++) { Logger.log(strategies[i][j]); } }
Return
WrapStrategy[][]
— A two-dimensional array of text wrapping strategies.
Authorization
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
getWrapStrategy()
Returns the text wrapping strategy for the top left cell of the range.
// Get the text wrapping strategy of cell B1. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B1:D4"); Logger.log(range.getWrapStrategy());
Return
WrapStrategy
— The text wrapping strategy of the top left cell in the range.
Authorization
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
getWraps()
Returns whether the text in the cells wrap. To get more granular wrap strategy, use getWrapStrategies()
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); var results = range.getVerticalAlignments(); for (var i in results) { for (var j in results[i]) { var isWrapped = results[i][j]; if (isWrapped) { Logger.log("Cell [%s, %s] has wrapped text", i, j); } } }
Return
Boolean[][]
— A two-dimensional array of vertical alignments of text associated with cells in the range.
Authorization
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
insertCells(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D10"); range.insertCells(SpreadsheetApp.Dimension.COLUMNS);
Parameters
Name | Type | Описание |
---|---|---|
shiftDimension | Dimension | The dimension along which to shift existing data. |
Return
Range
— This range, for chaining.
Authorization
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
insertCheckboxes()
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
.
var 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();
Return
Range
— This range, for chaining.
Authorization
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
insertCheckboxes(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.
var 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');
Parameters
Name | Type | Описание |
---|---|---|
checkedValue | Object | The checked value for the checkbox data validation. |
Return
Range
— This range, for chaining.
Authorization
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
insertCheckboxes(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.
var 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');
Parameters
Name | Type | Описание |
---|---|---|
checkedValue | Object | The checked value for the checkbox data validation. |
uncheckedValue | Object | The unchecked value for the checkbox data validation. |
Return
Range
— This range, for chaining.
Authorization
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
isBlank()
Returns true
if the range is totally blank.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.isBlank());
Return
Boolean
— true
if the range is blank; false
otherwise.
Authorization
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
isChecked()
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.
var range = SpreadsheetApp.getActive().getRange('A1:A3'); // Inserts checkboxes and sets each cell value to 'no' in the range A1:A3. range.insertCheckboxes('yes', 'no'); var range1 = SpreadsheetApp.getActive().getRange('A1'); range1.setValue('yes'); // Sets the value of isRange1Checked as true as it contains the checked value. var isRange1Checked = range1.isChecked(); var range2 = SpreadsheetApp.getActive().getRange('A2'); range2.setValue('no'); // Sets the value of isRange2Checked as false as it contains the unchecked value. var isRange2Checked = range2.isChecked(); var range3 = SpreadsheetApp.getActive().getRange('A3'); range3.setValue('random'); // Sets the value of isRange3Checked as null, as it contains an invalid checkbox value. var isRange3Checked = range3.isChecked();
Return
Boolean
— true
, 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.
Authorization
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
isEndColumnBounded()
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
.
Return
Boolean
— true
if the end of the range is bound to a particular column; false
otherwise.
Authorization
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
isEndRowBounded()
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
.
Return
Boolean
— true
if the end of the range is bound to a particular row; false
otherwise.
Authorization
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
isPartOfMerge()
Returns true
if the cells in the current range overlap any merged cells.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:B3"); // True if any of the cells in A1:B3 is included in a merge. var isPartOfMerge = range.isPartOfMerge();
Return
Boolean
— true
if the range overlaps any merged cells, otherwise returns false
.
isStartColumnBounded()
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
.
Return
Boolean
— true
if the start of the range is bound to a particular column; false
otherwise.
Authorization
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
isStartRowBounded()
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
.
Return
Boolean
— true
if the start of the range is bound to a particular row; false
otherwise.
Authorization
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
merge()
Merges the cells in the range together into a single block.
var sheet = SpreadsheetApp.getActiveSheet(); // The code below 2-dimensionally merges the cells in A1 to B3 sheet.getRange('A1:B3').merge();
Return
Range
— This range, for chaining.
Authorization
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
mergeAcross()
Merge the cells in the range across the columns of the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The code below merges cells C5:E5 into one cell var range1 = sheet.getRange("C5:E5"); range1.mergeAcross(); // The code below creates 2 horizontal cells, F5:H5 and F6:H6 var range2 = sheet.getRange("F5:H6"); range2.mergeAcross();
Return
Range
— This range, for chaining.
Authorization
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
mergeVertically()
Merges the cells in the range together.
var 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();
Return
Range
— This range, for chaining.
Authorization
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
moveTo(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 var sheet = SpreadsheetApp.getActiveSheet() sheet.getRange("A1:E").moveTo(sheet.getRange("F1"));
Parameters
Name | Type | Описание |
---|---|---|
target | Range | A target range to copy this range to; only the top-left cell position is relevant. |
Authorization
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
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("A1"); // newCell references B2 var newCell = cell.offset(1, 1);
Parameters
Name | Type | Описание |
---|---|---|
rowOffset | 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. |
columnOffset | 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. |
Return
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("A1"); // newCell references B2:B3 var newRange = cell.offset(1, 1, 2);
Parameters
Name | Type | Описание |
---|---|---|
rowOffset | 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. |
columnOffset | 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. |
numRows | Integer | The height in rows of the new range. |
Return
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("A1"); // newCell references B2:C3 var newRange = cell.offset(1, 1, 2, 2);
Parameters
Name | Type | Описание |
---|---|---|
rowOffset | 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. |
columnOffset | 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. |
numRows | Integer | The height in rows of the new range. |
numColumns | Integer | The width in columns of the new range. |
Return
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. var ss = SpreadsheetApp.getActive(); var range = ss.getRange('A1:B10'); var 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. var me = Session.getEffectiveUser(); protection.addEditor(me); protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); }
Return
Protection
— An object representing the protection settings.
Authorization
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
randomize()
Randomizes the order of the rows in the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:C7"); // Randomizes the range range.randomize();
Return
Range
— This range, for chaining.
Authorization
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
removeCheckboxes()
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.
var range = SpreadsheetApp.getActive().getRange('A1:B10'); // Inserts checkboxes and sets each cell value to 'no' in the range A1:B10. range.insertCheckboxes('yes', 'no'); var range1 = SpreadsheetApp.getActive().getRange('A1'); range1.setValue('yes'); // Removes the checkbox data validation in cell A1 and clears its value. range1.removeCheckboxes(); var range2 = SpreadsheetApp.getActive().getRange('A2'); range2.setValue('random'); // Removes the checkbox data validation in cell A2 but does not clear its value. range2.removeCheckboxes();
Return
Range
— This range, for chaining.
Authorization
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
removeDuplicates()
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B1:D7"); // Remove duplicate rows in the range. range.removeDuplicates();
Return
Range
— The resulting range after removing duplicates. The size of the range is reduced by a row for every row removed.
Authorization
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
removeDuplicates(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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]);
Parameters
Name | Type | Описание |
---|---|---|
columnsToCompare | Integer[] | The columns to analyze for duplicate values. If no columns are provided then all columns are analyzed for duplicates. |
Return
Range
— The resulting range after removing duplicates. The size of the range is reduced by a row for every row removed.
Authorization
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
setBackground(color)
Sets the background color of all cells in the range in CSS notation (such as '#ffffff'
or 'white'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D5"); range.setBackground("red");
Parameters
Name | Type | Описание |
---|---|---|
color | String | A color code in CSS notation (such as '#ffffff' or 'white' ); a null value resets the color. |
Return
Range
— This range, for chaining.
Authorization
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
setBackgroundObject(color)
Sets the background color of all cells in the range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var bgColor = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.BACKGROUND) .build(); var range = sheet.getRange("B2:D5"); range.setBackgroundObject(bgColor);
Parameters
Name | Type | Описание |
---|---|---|
color | Color | The background color to set; null value resets the background color. |
Return
Range
— This range, for chaining.
Authorization
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
setBackgroundObjects(color)
Sets a rectangular grid of background colors (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var colorAccent1 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT1) .build(); var colorAccent2 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT2) .build(); var colorAccent3 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT3) .build(); var colorAccent4 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT4) .build(); var colors = [ [colorAccent1, colorAccent2], [colorAccent3, colorAccent4] ]; var cell = sheet.getRange("B5:C6"); cell.setBackgroundObjects(colors);
Parameters
Name | Type | Описание |
---|---|---|
color | Color[][] | A two-dimensional array of colors; null values reset the color. |
Return
Range
— This range, for chaining.
Authorization
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
setBackgroundRGB(red, green, blue)
Sets the background to the given color using RGB values (integers between 0 and 255 inclusive).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); // Sets the background to white cell.setBackgroundRGB(255, 255, 255); // Sets the background to red cell.setBackgroundRGB(255, 0, 0);
Parameters
Name | Type | Описание |
---|---|---|
red | Integer | The red value in RGB notation. |
green | Integer | The green value in RGB notation. |
blue | Integer | The blue value in RGB notation. |
Return
Range
— This range, for chaining.
Authorization
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
setBackgrounds(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'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var colors = [ ["red", "white", "blue"], ["#FF0000", "#FFFFFF", "#0000FF"] // These are the hex equivalents ]; var cell = sheet.getRange("B5:D6"); cell.setBackgrounds(colors);
Parameters
Name | Type | Описание |
---|---|---|
color | String[][] | A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white' ); null values reset the color. |
Return
Range
— This range, for chaining.
Authorization
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
setBorder(top, left, bottom, right, vertical, horizontal)
Sets the border property. Valid values are true
(on), false
(off) and null
(no change).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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);
Parameters
Name | Type | Описание |
---|---|---|
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. |
Return
Range
— This range, for chaining.
Authorization
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
setBorder(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'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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);
Parameters
Name | Type | Описание |
---|---|---|
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 | BorderStyle | A style for the borders, null for default style (solid). |
Return
Range
— This range, for chaining.
Authorization
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
setDataValidation(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. var cell = SpreadsheetApp.getActive().getRange('A1'); var range = SpreadsheetApp.getActive().getRange('B1:B10'); var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range).build(); cell.setDataValidation(rule);
Parameters
Name | Type | Описание |
---|---|---|
rule | DataValidation | The data validation rule to set, or null to remove data validation. |
Return
Range
— This range, for chaining.
Authorization
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
setDataValidations(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. var destinationRange = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange('A1:B5'); var sourceRange = SpreadsheetApp.getActive().getSheetByName('Sheet2').getRange('A1:A10'); var rule = SpreadsheetApp.newDataValidation().requireValueInRange(sourceRange).build(); var rules = destinationRange.getDataValidations(); for (var i = 0; i < rules.length; i++) { for (var j = 0; j < rules[i].length; j++) { rules[i][j] = rule; } } destinationRange.setDataValidations(rules);
Parameters
Name | Type | Описание |
---|---|---|
rules | DataValidation[][] | A two-dimensional array of data validation rules to set; null values remove data validation. |
Return
Range
— This range, for chaining.
Authorization
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
setFontColor(color)
Sets the font color in CSS notation (such as '#ffffff'
or 'white'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontColor("red");
Parameters
Name | Type | Описание |
---|---|---|
color | String | The font color in CSS notation (such as '#ffffff' or 'white' ); a null value resets the color. |
Return
Range
— This range, for chaining.
Authorization
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
setFontColorObject(color)
Sets the font color of the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var color = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.TEXT) .build(); var cell = sheet.getRange("B2"); cell.setFontColor(color);
Parameters
Name | Type | Описание |
---|---|---|
color | Color | The font color to set; a null value resets the color. |
Return
Range
— This range, for chaining.
Authorization
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
setFontColorObjects(colors)
Sets a rectangular grid of font colors (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var colorAccent1 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT1) .build(); var colorAccent2 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT2) .build(); var colorAccent3 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT3) .build(); var colorAccent4 = SpreadsheetApp.newColor() .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT4) .build(); var colors = [ [colorAccent1, colorAccent2], [colorAccent3, colorAccent4] ]; var cell = sheet.getRange("B5:C6"); cell.setFontColorObjects(colors);
Parameters
Name | Type | Описание |
---|---|---|
colors | Color[][] | A two-dimensional array of colors; null values reset the font color. |
Return
Range
— This range, for chaining.
Authorization
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
setFontColors(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'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var colors = [ ["red", "white", "blue"], ["#FF0000", "#FFFFFF", "#0000FF"] // These are the hex equivalents ]; var cell = sheet.getRange("B5:D6"); cell.setFontColors(colors);
Parameters
Name | Type | Описание |
---|---|---|
colors | Object[][] | A two-dimensional array of colors in CSS notation (such as '#ffffff' or 'white' ); null values reset the color. |
Return
Range
— This range, for chaining.
Authorization
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
setFontFamilies(fontFamilies)
Sets a rectangular grid of font families (must match dimensions of this range). Examples of font families are "Arial" or "Helvetica".
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var fonts = [ ["Arial", "Helvetica", "Verdana"], ["Courier New", "Arial", "Helvetica] ]; var cell = sheet.getRange("B2:D3"); cell.setFontFamilies(fonts);
Parameters
Name | Type | Описание |
---|---|---|
fontFamilies | Object[][] | A two-dimensional array of font families; null values reset the font family. |
Return
Range
— This range, for chaining.
Authorization
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
setFontFamily(fontFamily)
Sets the font family, such as "Arial" or "Helvetica".
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontFamily("Helvetica");
Parameters
Name | Type | Описание |
---|---|---|
fontFamily | String | The font family to set; a null value resets the font family. |
Return
Range
— This range, for chaining.
Authorization
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
setFontLine(fontLine)
Sets the font line style of the given range ( 'underline'
, 'line-through'
, or 'none'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontLine("line-through");
Parameters
Name | Type | Описание |
---|---|---|
fontLine | String | The font line style, either 'underline' , 'line-through' , or 'none' ; a null value resets the font line style. |
Return
Range
— This range, for chaining.
Authorization
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
setFontLines(fontLines)
Sets a rectangular grid of line styles (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var fontLines = [ ["underline", "line-through", "none"] ]; var range = sheet.getRange("B2:D2"); range.setFontLines(fontLines);
Parameters
Name | Type | Описание |
---|---|---|
fontLines | Object[][] | A two-dimensional array of font line styles ( 'underline' , 'line-through' , or 'none' ); null values reset the font line style. |
Return
Range
— This range, for chaining.
Authorization
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
setFontSize(size)
Sets the font size, with the size being the point size to use.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontSize(20);
Parameters
Name | Type | Описание |
---|---|---|
size | Integer | A font size in point size. |
Return
Range
— This range, for chaining.
Authorization
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
setFontSizes(sizes)
Sets a rectangular grid of font sizes (must match dimensions of this range). The sizes are in points.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var fontSizes = [ [16, 20, 24] ]; var range = sheet.getRange("B2:D2"); range.setFontSizes(fontSizes);
Parameters
Name | Type | Описание |
---|---|---|
sizes | Object[][] | A two-dimensional array of sizes. |
Return
Range
— This range, for chaining.
Authorization
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
setFontStyle(fontStyle)
Set the font style for the given range ( 'italic'
or 'normal'
).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontStyle("italic");
Parameters
Name | Type | Описание |
---|---|---|
fontStyle | String | The font style, either 'italic' or 'normal' ; a null value resets the font style. |
Return
Range
— This range, for chaining.
Authorization
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
setFontStyles(fontStyles)
Sets a rectangular grid of font styles (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var fontStyles = [ ["italic", "normal"] ]; var range = sheet.getRange("B2:C2"); range.setFontStyles(fontStyles);
Parameters
Name | Type | Описание |
---|---|---|
fontStyles | Object[][] | A two-dimensional array of font styles, either 'italic' or 'normal' ; null values reset the font style. |
Return
Range
— This range, for chaining.
Authorization
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
setFontWeight(fontWeight)
Set the font weight for the given range (normal/bold).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setFontWeight("bold");
Parameters
Name | Type | Описание |
---|---|---|
fontWeight | String | The font weight, either 'bold' or 'normal' ; a null value resets the font weight. |
Return
Range
— This range, for chaining.
Authorization
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
setFontWeights(fontWeights)
Sets a rectangular grid of font weights (must match dimensions of this range). An example of a font weight is "bold".
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var fontStyles = [ [ "bold", "bold", "normal" ] ]; var range = sheet.getRange("B2:D2"); range.setFontWeights(fontStyles);
Parameters
Name | Type | Описание |
---|---|---|
fontWeights | Object[][] | A two-dimensional array of font weights, either 'bold' or 'normal' ; null values reset the font weight. |
Return
Range
— This range, for chaining.
Authorization
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
setFormula(formula)
Updates the formula for this range. The given formula must be in A1 notation.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B5"); cell.setFormula("=SUM(B3:B4)");
Parameters
Name | Type | Описание |
---|---|---|
formula | String | A string representing the formula to set for the cell. |
Return
Range
— This range, for chaining.
Authorization
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
setFormulaR1C1(formula)
Updates the formula for this range. The given formula must be in R1C1 notation.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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])");
Parameters
Name | Type | Описание |
---|---|---|
formula | String | A string formula. |
Return
Range
— This range, for chaining.
Authorization
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
setFormulas(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var 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. var formulas = [ ["=SUM(B2:B4)", "=SUM(C2:C4)", "=SUM(D2:D4)"], ["=AVERAGE(B2:B4)", "=AVERAGE(C2:C4)", "=AVERAGE(D2:D4)"] ]; var cell = sheet.getRange("B5:D6"); cell.setFormulas(formulas);
Parameters
Name | Type | Описание |
---|---|---|
formulas | String[][] | A two-dimensional string array of formulas. |
Return
Range
— This range, for chaining.
Authorization
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
setFormulasR1C1(formulas)
Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in R1C1 notation.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This creates formulas for a row of sums, followed by a row of averages. var sumOfRowsAbove = "=SUM(R[-3]C[0]:R[-1]C[0])"; var averageOfRowsAbove = "=AVERAGE(R[-4]C[0]:R[-2]C[0])"; // The size of the two-dimensional array must match the size of the range. var formulas = [ [sumOfRowsAbove, sumOfRowsAbove, sumOfRowsAbove], [averageOfRowsAbove, averageOfRowsAbove, averageOfRowsAbove] ]; var cell = sheet.getRange("B5:D6"); // This sets the formula to be the sum of the 3 rows above B5. cell.setFormulasR1C1(formulas);
Parameters
Name | Type | Описание |
---|---|---|
formulas | String[][] | A two-dimensional array of formulas in R1C1 format. |
Return
Range
— This range, for chaining.
Authorization
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
setHorizontalAlignment(alignment)
Set the horizontal (left to right) alignment for the given range (left/center/right).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setHorizontalAlignment("center");
Parameters
Name | Type | Описание |
---|---|---|
alignment | String | The alignment, either 'left' , 'center' or 'normal' ; a null value resets the alignment. |
Return
Range
— This range, for chaining.
Authorization
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
setHorizontalAlignments(alignments)
Sets a rectangular grid of horizontal alignments. see setHorizontalAlignment(alignment)
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var horizontalAlignments = [ [ "left", "right", "center" ] ]; var range = sheet.getRange("B2:D2"); range.setHorizontalAlignments(horizontalAlignments);
Parameters
Name | Type | Описание |
---|---|---|
alignments | Object[][] | A two-dimensional array of alignments, either 'left' , 'center' or 'normal' ; a null value resets the alignment. |
Return
Range
— This range, for chaining.
Authorization
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
See also
setNote(note)
Sets the note to the given value.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setNote("This is a note");
Parameters
Name | Type | Описание |
---|---|---|
note | String | The note value to set for the range; a null value removes the note. |
Return
Range
— This range, for chaining.
Authorization
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
setNotes(notes)
Sets a rectangular grid of notes (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var notes = [ ["it goes", "like this", "the fourth, the fifth"], ["the minor fall", "and the", "major lift"] ]; var cell = sheet.getRange("B2:D3"); cell.setNotes(notes)
Parameters
Name | Type | Описание |
---|---|---|
notes | Object[][] | A two-dimensional array of notes; null values remove the note. |
Return
Range
— This range, for chaining.
Authorization
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
See also
setNumberFormat(numberFormat)
Sets the number or date format to the given formatting string. The accepted format patterns are described in the Sheets API documentation .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); // Always show 3 decimal points cell.setNumberFormat("0.000");
Parameters
Name | Type | Описание |
---|---|---|
numberFormat | String | A number format string. |
Return
Range
— This range, for chaining.
Authorization
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
setNumberFormats(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 .
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var formats = [ [ "0.000", "0,000,000", "$0.00" ] ]; var range = sheet.getRange("B2:D2"); range.setNumberFormats(formats);
Parameters
Name | Type | Описание |
---|---|---|
numberFormats | Object[][] | A two-dimensional array of number formats. |
Return
Range
— This range, for chaining.
Authorization
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
setRichTextValue(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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B2:D4"); var bold = SpreadsheetApp.newTextStyle() .setBold(true) .build(); var richText = SpreadsheetApp.newRichTextValue() .setText("Hello world") .setTextStyle(0, 5, bold) .build(); range.setRichTextValue(richText);
Parameters
Name | Type | Описание |
---|---|---|
value | RichTextValue | The desired Rich Text value. |
Return
Range
— This range, for chaining.
Authorization
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
setRichTextValues(values)
Sets a rectangular grid of Rich Text values.
// Sets the cells in range A1:A2 to have Rich Text values. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("A1:A2"); var bold = SpreadsheetApp.newTextStyle() .setBold(true) .build(); var italic = SpreadsheetApp.newTextStyle() .setItalic(true) .build(); var richTextA1 = SpreadsheetApp.newRichTextValue() .setText("This cell is bold") .setTextStyle(bold) .build(); var richTextA2 = SpreadsheetApp.newRichTextValue() .setText("bold words, italic words") .setTextStyle(0, 11, bold) .setTextStyle(12, 24, italic) .build(); range.setRichTextValues([[richTextA1], [richTextA2]]);
Parameters
Name | Type | Описание |
---|---|---|
values | RichTextValue[][] | The desired Rich Text values. |
Return
Range
— This range, for chaining.
Authorization
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
setShowHyperlink(showHyperlink)
Sets whether or not the range should show hyperlinks.
Parameters
Name | Type | Описание |
---|---|---|
showHyperlink | Boolean | Whether or not to show the hyperlink. |
Return
Range
— This range, for chaining.
Authorization
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
setTextDirection(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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B5:C6"); range.setTextDirection(SpreadsheetApp.TextDirection.RIGHT_TO_LEFT);
Parameters
Name | Type | Описание |
---|---|---|
direction | TextDirection | The desired text direction; if null the direction is inferred before setting. |
Return
Range
— This range, for chaining.
Authorization
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
setTextDirections(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. var sheet = SpreadsheetApp.getActiveSheet(); var range1 = sheet.getRange("A1:B2"); var range2 = sheet.getRange("C5:D6"); range2.setTextRotations(range1.getTextDirections());
Parameters
Name | Type | Описание |
---|---|---|
directions | TextDirection[][] | The desired text directions; if a specified direction is null it is inferred before setting. |
Return
Range
— This range, for chaining.
Authorization
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
setTextRotation(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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B2:D4"); range.setTextRotation(45);
Parameters
Name | Type | Описание |
---|---|---|
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. |
Return
Range
— This range, for chaining.
Authorization
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
setTextRotation(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. var sheet = SpreadsheetApp.getActiveSheet(); var rotation = sheet.getRange("A1").getTextRotation(); sheet.getRange("B2:D4").setTextRotation(rotation);
Parameters
Name | Type | Описание |
---|---|---|
rotation | TextRotation | The desired text rotation settings. |
Return
Range
— This range, for chaining.
Authorization
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
setTextRotations(rotations)
Sets a rectangular grid of text rotations.
// Copies all of the text rotations from range A1:B2 over to range C5:D6. var sheet = SpreadsheetApp.getActiveSheet(); var range1 = sheet.getRange("A1:B2"); var range2 = sheet.getRange("C5:D6"); range2.setTextRotations(range1.getTextRotations());
Parameters
Name | Type | Описание |
---|---|---|
rotations | TextRotation[][] | The desired text rotation settings. |
Return
Range
— This range, for chaining.
Authorization
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
setTextStyle(style)
Sets the text style for the cells in the range.
// Sets the cells in range C5:D6 to have underlined size 15 font. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("C5:D6"); var style = SpreadsheetApp.newTextStyle() .setFontSize(15) .setUnderline(true) .build(); range.setTextStyle(style);
Parameters
Name | Type | Описание |
---|---|---|
style | TextStyle | The desired text style. |
Return
Range
— This range, for chaining.
Authorization
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
setTextStyles(styles)
Sets a rectangular grid of text styles.
// Sets text styles for cells in range A1:B2 var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("A1:B2"); var bold = SpreadsheetApp.newTextStyle() .setBold(true) .build(); var otherStyle = SpreadsheetApp.newTextStyle() .setBold(true) .setUnderline(true) .setItalic(true) .setForegroundColor("#335522") .setFontSize(44) .build(); range.setTextStyles([[bold, otherStyle], [otherStyle, bold]]);
Parameters
Name | Type | Описание |
---|---|---|
styles | TextStyle[][] | The desired text styles. |
Return
Range
— This range, for chaining.
Authorization
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
setValue(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setValue(100);
Parameters
Name | Type | Описание |
---|---|---|
value | Object | The value for the range. |
Return
Range
— This range, for chaining.
Authorization
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
setValues(values)
Sets a rectangular grid of values (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var values = [ [ "2.000", "1,000,000", "$2.99" ] ]; var range = sheet.getRange("B2:D2"); range.setValues(values);
Parameters
Name | Type | Описание |
---|---|---|
values | Object[][] | A two-dimensional array of values. |
Return
Range
— This range, for chaining.
Authorization
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
setVerticalAlignment(alignment)
Set the vertical (top to bottom) alignment for the given range (top/middle/bottom).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setVerticalAlignment("middle");
Parameters
Name | Type | Описание |
---|---|---|
alignment | String | The alignment, either 'top' , 'middle' or 'bottom' ; a null value resets the alignment. |
Return
Range
— This range, for chaining.
Authorization
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
setVerticalAlignments(alignments)
Sets a rectangular grid of vertical alignments (must match dimensions of this range).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var alignments = [ [ "top", "middle", "bottom" ] ]; var range = sheet.getRange("B2:D2"); range.setVerticalAlignments(alignments);
Parameters
Name | Type | Описание |
---|---|---|
alignments | Object[][] | A two-dimensional array of alignments, either 'top' , 'middle' or 'bottom' ; a null value resets the alignment. |
Return
Range
— This range, for chaining.
Authorization
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
See also
setVerticalText(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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B2:D4"); range.setVerticalText(true);
Parameters
Name | Type | Описание |
---|---|---|
isVertical | Boolean | Whether or not to stack the text. |
Return
Range
— This range, for chaining.
Authorization
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
setWrap(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var cell = sheet.getRange("B2"); cell.setWrap(true);
Parameters
Name | Type | Описание |
---|---|---|
isWrapEnabled | Boolean | Whether to wrap text or not. |
Return
Range
— This range, for chaining.
Authorization
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
setWrapStrategies(strategies)
Sets a rectangular grid of wrap strategies.
// Copies all of the wrap strategies from range A1:B2 over to range C5:D6. var sheet = SpreadsheetApp.getActiveSheet(); var range1 = sheet.getRange("A1:B2"); var range2 = sheet.getRange("C5:D6"); range2.setWrapStrategies(range1.getWrapStrategies());
Parameters
Name | Type | Описание |
---|---|---|
strategies | WrapStrategy[][] | The desired wrapping strategies. |
Return
Range
— This range, for chaining.
Authorization
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
setWrapStrategy(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. var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("B2:D4"); range.setWrapStrategy(SpreadsheetApp.WrapStrategy.CLIP);
Parameters
Name | Type | Описание |
---|---|---|
strategy | WrapStrategy | The desired wrapping strategy. |
Return
Range
— This range, for chaining.
Authorization
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
setWraps(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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The size of the two-dimensional array must match the size of the range. var wraps = [ [ true, true, false ] ]; var range = sheet.getRange("B2:D2"); range.setWraps(wraps);
Parameters
Name | Type | Описание |
---|---|---|
isWrapEnabled | Object[][] | A two-dimensional array of wrap variables that determine whether to wrap text in a cell or not. |
Return
Range
— This range, for chaining.
Authorization
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
See also
shiftColumnGroupDepth(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.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var 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);
Parameters
Name | Type | Описание |
---|---|---|
delta | Integer | The amount by which to change the column group depth of this range. |
Return
Range
— This range, for chaining.
Throws
Error
— when attempting to shift the depth of the first column when the control position is GroupControlTogglePosition.BEFORE
Authorization
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
shiftRowGroupDepth(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.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var 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);
Parameters
Name | Type | Описание |
---|---|---|
delta | Integer | The amount by which to change the row group depth of this range. |
Return
Range
— This range, for chaining.
Throws
Error
— when attempting to shift the depth of the first row when the control position is GroupControlTogglePosition.BEFORE
Authorization
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.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var 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}]);
Parameters
Name | Type | Описание |
---|---|---|
sortSpecObj | Object | The columns to sort by. |
Return
Range
— This range, for chaining.
Authorization
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
splitTextToColumns()
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| | | var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3"); range.splitTextToColumns(); // Result after spliting the text to columns: // A B C // 1 |one |one |one | // 2 |two |two |two | // 3 |three |three |three |
Authorization
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
splitTextToColumns(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| | | var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3"); range.splitTextToColumns('#'); // Result after spliting the text to columns: // A B C // 1 |one |one |one | // 2 |two |two |two | // 3 |three |three |three |
Parameters
Name | Type | Описание |
---|---|---|
delimiter | String | The custom delimiter to split on. |
Authorization
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
splitTextToColumns(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| | | var range = SpreadsheetApp.getActiveSheet().getRange("A1:A3"); range.splitTextToColumns(SpreadsheetApp.TextToColumnsDelimiter.SEMICOLON); // Result after spliting the text to columns: // A B C // 1 |one |one |one | // 2 |two |two |two | // 3 |three |three |three |
Parameters
Name | Type | Описание |
---|---|---|
delimiter | TextToColumnsDelimiter | The preset delimiter to split on. |
Authorization
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
trimWhitespace()
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.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; var range = sheet.getRange('A1:A4'); range.activate(); range.setValues( [' preceding space', 'following space ', 'two middle spaces', ' =SUM(1,2)']) range.trimWhitespace(); var values = range.getValues(); // Values are ['preceding space', 'following space', 'two middle spaces', '=SUM(1,2)']
Return
Range
— This range, for chaining.
Authorization
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'. var range = SpreadsheetApp.getActive().getRange('A1:B10'); range.uncheck();
Return
Range
— This range, for chaining.
Authorization
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