Доступ и изменение файлов Google Sheets. Распространенными операциями являются добавление новых листов и добавление соавторов.
Методы
Метод | Тип возврата | Краткое описание |
---|---|---|
addDeveloperMetadata(key) | Spreadsheet | Добавляет метаданные разработчика с указанным ключом в электронную таблицу верхнего уровня. |
addDeveloperMetadata(key, visibility) | Spreadsheet | Добавляет метаданные разработчика с указанным ключом и видимостью в электронную таблицу. |
addDeveloperMetadata(key, value) | Spreadsheet | Добавляет метаданные разработчика с указанным ключом и значением в электронную таблицу. |
addDeveloperMetadata(key, value, visibility) | Spreadsheet | Добавляет метаданные разработчика с указанным ключом, значением и видимостью в электронную таблицу. |
addEditor(emailAddress) | Spreadsheet | Добавляет данного пользователя в список редакторов Spreadsheet . |
addEditor(user) | Spreadsheet | Добавляет данного пользователя в список редакторов Spreadsheet . |
addEditors(emailAddresses) | Spreadsheet | Добавляет заданный массив пользователей в список редакторов Spreadsheet . |
addMenu(name, subMenus) | void | Создает новое меню в пользовательском интерфейсе электронных таблиц. |
addViewer(emailAddress) | Spreadsheet | Добавляет данного пользователя в список зрителей Spreadsheet . |
addViewer(user) | Spreadsheet | Добавляет данного пользователя в список зрителей Spreadsheet . |
addViewers(emailAddresses) | Spreadsheet | Добавляет указанный массив пользователей в список зрителей Spreadsheet . |
appendRow(rowContents) | Sheet | Добавляет строку в конец текущей области данных на листе. |
autoResizeColumn(columnPosition) | Sheet | Устанавливает ширину данного столбца в соответствии с его содержимым. |
copy(name) | Spreadsheet | Копирует электронную таблицу и возвращает новую. |
createDeveloperMetadataFinder() | DeveloperMetadataFinder | Возвращает DeveloperMetadataFinder для поиска метаданных разработчика в рамках этой электронной таблицы. |
createTextFinder(findText) | TextFinder | Создает средство поиска текста для электронной таблицы, которое можно использовать для поиска и замены текста в электронной таблице. |
deleteActiveSheet() | Sheet | Удаляет текущий активный лист. |
deleteColumn(columnPosition) | Sheet | Удаляет столбец в заданной позиции столбца. |
deleteColumns(columnPosition, howMany) | void | Удаляет ряд столбцов, начиная с данной позиции столбца. |
deleteRow(rowPosition) | Sheet | Удаляет строку в заданной позиции строки. |
deleteRows(rowPosition, howMany) | void | Удаляет ряд строк, начиная с заданной позиции строки. |
deleteSheet(sheet) | void | Удаляет указанный лист. |
duplicateActiveSheet() | Sheet | Дублирует активный лист и делает его активным листом. |
getActiveCell() | Range | Возвращает активную ячейку на этом листе. |
getActiveRange() | Range | Возвращает выбранный диапазон на активном листе или null , если активного диапазона нет. |
getActiveRangeList() | RangeList | Возвращает список активных диапазонов на активном листе или null , если активных диапазонов нет. |
getActiveSheet() | Sheet | Получает активный лист электронной таблицы. |
getAs(contentType) | Blob | Верните данные внутри этого объекта в виде большого двоичного объекта, преобразованного в указанный тип контента. |
getBandings() | Banding[] | Возвращает все полосы в этой электронной таблице. |
getBlob() | Blob | Верните данные внутри этого объекта в виде большого двоичного объекта. |
getColumnWidth(columnPosition) | Integer | Получает ширину в пикселях данного столбца. |
getCurrentCell() | Range | Возвращает текущую ячейку на активном листе или null , если текущей ячейки нет. |
getDataRange() | Range | Возвращает Range , соответствующий измерениям, в которых присутствуют данные. |
getDataSourceFormulas() | DataSourceFormula[] | Получает все формулы источника данных. |
getDataSourcePivotTables() | DataSourcePivotTable[] | Получает все сводные таблицы источников данных. |
getDataSourceRefreshSchedules() | DataSourceRefreshSchedule[] | Получает расписания обновления этой электронной таблицы. |
getDataSourceSheets() | DataSourceSheet[] | Возвращает все листы источника данных в электронной таблице. |
getDataSourceTables() | DataSourceTable[] | Получает все таблицы источников данных. |
getDataSources() | DataSource[] | Возвращает все источники данных в электронной таблице. |
getDeveloperMetadata() | DeveloperMetadata[] | Получите метаданные разработчика, связанные с электронной таблицей верхнего уровня. |
getEditors() | User[] | Получает список редакторов для этой Spreadsheet . |
getFormUrl() | String | Возвращает URL-адрес формы, которая отправляет свои ответы в эту электронную таблицу, или null если эта электронная таблица не имеет связанной формы. |
getFrozenColumns() | Integer | Возвращает количество замороженных столбцов. |
getFrozenRows() | Integer | Возвращает количество замороженных строк. |
getId() | String | Получает уникальный идентификатор для этой электронной таблицы. |
getImages() | OverGridImage[] | Возвращает все изображения поверх сетки на листе. |
getIterativeCalculationConvergenceThreshold() | Number | Возвращает пороговое значение, используемое во время итеративного вычисления. |
getLastColumn() | Integer | Возвращает позицию последнего столбца с содержимым. |
getLastRow() | Integer | Возвращает позицию последней строки с содержимым. |
getMaxIterativeCalculationCycles() | Integer | Возвращает максимальное количество итераций для использования во время итеративного вычисления. |
getName() | String | Получает имя документа. |
getNamedRanges() | NamedRange[] | Получает все именованные диапазоны в этой электронной таблице. |
getNumSheets() | Integer | Возвращает количество листов в этой электронной таблице. |
getOwner() | User | Возвращает владельца документа или null для документа на общем диске. |
getPredefinedSpreadsheetThemes() | SpreadsheetTheme[] | Возвращает список предопределенных тем. |
getProtections(type) | Protection[] | Получает массив объектов, представляющих все защищенные диапазоны или листы в электронной таблице. |
getRange(a1Notation) | Range | Возвращает диапазон, указанный в нотации A1 или нотации R1C1. |
getRangeByName(name) | Range | Возвращает именованный диапазон или null , если диапазон с заданным именем не найден. |
getRangeList(a1Notations) | RangeList | Возвращает коллекцию RangeList , представляющую диапазоны на одном листе, указанном непустым списком нотаций A1 или R1C1. |
getRecalculationInterval() | RecalculationInterval | Возвращает интервал расчета для этой электронной таблицы. |
getRowHeight(rowPosition) | Integer | Получает высоту в пикселях данной строки. |
getSelection() | Selection | Возвращает текущий Selection в электронной таблице. |
getSheetByName(name) | Sheet | Возвращает лист с заданным именем. |
getSheetId() | Integer | Возвращает идентификатор листа, представленного этим объектом. |
getSheetName() | String | Возвращает имя листа. |
getSheetValues(startRow, startColumn, numRows, numColumns) | Object[][] | Возвращает прямоугольную сетку значений для этого диапазона, начиная с заданных координат. |
getSheets() | Sheet[] | Получает все листы в этой электронной таблице. |
getSpreadsheetLocale() | String | Получает языковой стандарт электронной таблицы. |
getSpreadsheetTheme() | SpreadsheetTheme | Возвращает текущую тему электронной таблицы или null , если тема не применена. |
getSpreadsheetTimeZone() | String | Получает часовой пояс для электронной таблицы. |
getUrl() | String | Возвращает URL для данной электронной таблицы. |
getViewers() | User[] | Получает список зрителей и комментаторов для этой Spreadsheet . |
hideColumn(column) | void | Скрывает столбец или столбцы в заданном диапазоне. |
hideRow(row) | void | Скрывает строки в заданном диапазоне. |
insertColumnAfter(afterPosition) | Sheet | Вставляет столбец после заданной позиции столбца. |
insertColumnBefore(beforePosition) | Sheet | Вставляет столбец перед заданной позицией столбца. |
insertColumnsAfter(afterPosition, howMany) | Sheet | Вставляет количество столбцов после заданной позиции столбца. |
insertColumnsBefore(beforePosition, howMany) | Sheet | Вставляет несколько столбцов перед заданной позицией столбца. |
insertDataSourceSheet(spec) | DataSourceSheet | Вставляет новый DataSourceSheet в электронную таблицу и запускает выполнение данных. |
insertImage(blobSource, column, row) | OverGridImage | Вставляет Spreadsheet как изображение в документ в заданной строке и столбце. |
insertImage(blobSource, column, row, offsetX, offsetY) | OverGridImage | Вставляет Spreadsheet как изображение в документ в заданной строке и столбце со смещением в пикселях. |
insertImage(url, column, row) | OverGridImage | Вставляет изображение в документ в заданную строку и столбец. |
insertImage(url, column, row, offsetX, offsetY) | OverGridImage | Вставляет изображение в документ в указанную строку и столбец со смещением в пикселях. |
insertRowAfter(afterPosition) | Sheet | Вставляет строку после заданной позиции строки. |
insertRowBefore(beforePosition) | Sheet | Вставляет строку перед заданной позицией строки. |
insertRowsAfter(afterPosition, howMany) | Sheet | Вставляет ряд строк после заданной позиции строки. |
insertRowsBefore(beforePosition, howMany) | Sheet | Вставляет ряд строк перед заданной позицией строки. |
insertSheet() | Sheet | Вставляет новый лист в электронную таблицу, используя имя листа по умолчанию. |
insertSheet(sheetIndex) | Sheet | Вставляет новый лист в электронную таблицу с заданным индексом. |
insertSheet(sheetIndex, options) | Sheet | Вставляет новый лист в электронную таблицу по заданному индексу и использует необязательные расширенные аргументы. |
insertSheet(options) | Sheet | Вставляет новый лист в электронную таблицу, используя имя листа по умолчанию и необязательные расширенные аргументы. |
insertSheet(sheetName) | Sheet | Вставляет новый лист в электронную таблицу с заданным именем. |
insertSheet(sheetName, sheetIndex) | Sheet | Вставляет новый лист в электронную таблицу с заданным именем по заданному индексу. |
insertSheet(sheetName, sheetIndex, options) | Sheet | Вставляет новый лист в электронную таблицу с заданным именем по заданному индексу и использует необязательные расширенные аргументы. |
insertSheet(sheetName, options) | Sheet | Вставляет новый лист в электронную таблицу с заданным именем и использует необязательные расширенные аргументы. |
insertSheetWithDataSourceTable(spec) | Sheet | Вставляет новый лист в электронную таблицу, создает DataSourceTable , охватывающую весь лист с заданной спецификацией источника данных, и запускает выполнение данных. |
isColumnHiddenByUser(columnPosition) | Boolean | Возвращает, скрыт ли данный столбец пользователем. |
isIterativeCalculationEnabled() | Boolean | Возвращает значение, включенное ли итеративное вычисление в этой электронной таблице. |
isRowHiddenByFilter(rowPosition) | Boolean | Возвращает, скрыта ли данная строка фильтром (не представлением фильтра). |
isRowHiddenByUser(rowPosition) | Boolean | Возвращает, скрыта ли данная строка пользователем. |
moveActiveSheet(pos) | void | Перемещает активный лист в заданную позицию в списке листов. |
moveChartToObjectSheet(chart) | Sheet | Создает новый лист SheetType.OBJECT и перемещает на него предоставленную диаграмму. |
refreshAllDataSources() | void | Обновляет все поддерживаемые источники данных и связанные с ними объекты источников данных, пропуская недопустимые объекты источников данных. |
removeEditor(emailAddress) | Spreadsheet | Удаляет данного пользователя из списка редакторов Spreadsheet . |
removeEditor(user) | Spreadsheet | Удаляет данного пользователя из списка редакторов Spreadsheet . |
removeMenu(name) | void | Удаляет меню, которое было добавлено addMenu(name, subMenus) . |
removeNamedRange(name) | void | Удаляет именованный диапазон с заданным именем. |
removeViewer(emailAddress) | Spreadsheet | Удаляет данного пользователя из списка зрителей и комментаторов Spreadsheet . |
removeViewer(user) | Spreadsheet | Удаляет данного пользователя из списка зрителей и комментаторов Spreadsheet . |
rename(newName) | void | Переименовывает документ. |
renameActiveSheet(newName) | void | Переименовывает текущий активный лист в заданное новое имя. |
resetSpreadsheetTheme() | SpreadsheetTheme | Удаляет примененную тему и устанавливает тему по умолчанию для электронной таблицы. |
setActiveRange(range) | Range | Устанавливает указанный диапазон в качестве active range на активном листе, при этом верхняя левая ячейка в диапазоне является current cell . |
setActiveRangeList(rangeList) | RangeList | Задает указанный список диапазонов в качестве active ranges на активном листе. |
setActiveSelection(range) | Range | Устанавливает активную область выбора для этого листа. |
setActiveSelection(a1Notation) | Range | Устанавливает активный выбор, как указано в нотации A1 или нотации R1C1. |
setActiveSheet(sheet) | Sheet | Устанавливает данный лист в качестве активного листа в электронной таблице. |
setActiveSheet(sheet, restoreSelection) | Sheet | Устанавливает данный лист в качестве активного листа в электронной таблице с возможностью восстановления самого последнего выбора на этом листе. |
setColumnWidth(columnPosition, width) | Sheet | Устанавливает ширину данного столбца в пикселях. |
setCurrentCell(cell) | Range | Устанавливает указанную ячейку в качестве current cell . |
setFrozenColumns(columns) | void | Замораживает заданное количество столбцов. |
setFrozenRows(rows) | void | Замораживает заданное количество строк. |
setIterativeCalculationConvergenceThreshold(minThreshold) | Spreadsheet | Задает минимальное пороговое значение для итеративного расчета. |
setIterativeCalculationEnabled(isEnabled) | Spreadsheet | Устанавливает, включен ли итеративный расчет в этой электронной таблице. |
setMaxIterativeCalculationCycles(maxIterations) | Spreadsheet | Задает максимальное количество итераций вычисления, которое должно быть выполнено во время итеративного вычисления. |
setNamedRange(name, range) | void | Называет диапазон. |
setRecalculationInterval(recalculationInterval) | Spreadsheet | Устанавливает, как часто эта электронная таблица должна пересчитываться. |
setRowHeight(rowPosition, height) | Sheet | Устанавливает высоту строки данной строки в пикселях. |
setSpreadsheetLocale(locale) | void | Устанавливает языковой стандарт электронной таблицы. |
setSpreadsheetTheme(theme) | SpreadsheetTheme | Устанавливает тему в электронной таблице. |
setSpreadsheetTimeZone(timezone) | void | Устанавливает часовой пояс для электронной таблицы. |
show(userInterface) | void | Отображает настраиваемый компонент пользовательского интерфейса в диалоговом окне с центром в окне просмотра браузера пользователя. |
sort(columnPosition) | Sheet | Сортирует лист по столбцу по возрастанию. |
sort(columnPosition, ascending) | Sheet | Сортирует лист по столбцу. |
toast(msg) | void | Показывает всплывающее окно в правом нижнем углу электронной таблицы с заданным сообщением. |
toast(msg, title) | void | Показывает всплывающее окно в правом нижнем углу электронной таблицы с заданным сообщением и заголовком. |
toast(msg, title, timeoutSeconds) | void | Показывает всплывающее окно в правом нижнем углу электронной таблицы с заданным заголовком и сообщением, которое остается видимым в течение определенного периода времени. |
unhideColumn(column) | void | Отображает столбец в заданном диапазоне. |
unhideRow(row) | void | Отображает строку в заданном диапазоне. |
updateMenu(name, subMenus) | void | Обновляет меню, добавленное с помощью addMenu(name, subMenus) . |
waitForAllDataExecutionsCompletion(timeoutInSeconds) | void | Ожидает завершения всех текущих выполнений в электронной таблице, время ожидания истекает через указанное количество секунд. |
Подробная документация
addDeveloperMetadata(key)
Добавляет метаданные разработчика с указанным ключом в электронную таблицу верхнего уровня.
Параметры
Имя | Тип | Описание |
---|---|---|
key | String | Ключ для новых метаданных разработчика. |
Возвращаться
Spreadsheet
— Эта электронная таблица для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addDeveloperMetadata(key, visibility)
Добавляет метаданные разработчика с указанным ключом и видимостью в электронную таблицу.
Параметры
Имя | Тип | Описание |
---|---|---|
key | String | Ключ для новых метаданных разработчика. |
visibility | DeveloperMetadataVisibility | Видимость новых метаданных разработчика. |
Возвращаться
Spreadsheet
— Эта электронная таблица для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addDeveloperMetadata(key, value)
Добавляет метаданные разработчика с указанным ключом и значением в электронную таблицу.
Параметры
Имя | Тип | Описание |
---|---|---|
key | String | Ключ для новых метаданных разработчика. |
value | String | Значение для новых метаданных разработчика. |
Возвращаться
Spreadsheet
— Эта электронная таблица для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addDeveloperMetadata(key, value, visibility)
Добавляет метаданные разработчика с указанным ключом, значением и видимостью в электронную таблицу.
Параметры
Имя | Тип | Описание |
---|---|---|
key | String | Ключ для новых метаданных разработчика. |
value | String | Значение для новых метаданных разработчика. |
visibility | DeveloperMetadataVisibility | Видимость новых метаданных разработчика. |
Возвращаться
Spreadsheet
— Эта электронная таблица для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addEditor(emailAddress)
Добавляет данного пользователя в список редакторов Spreadsheet
. Если пользователь уже был в списке зрителей, этот метод продвигает пользователя из списка зрителей.
Параметры
Имя | Тип | Описание |
---|---|---|
emailAddress | String | Адрес электронной почты добавляемого пользователя. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addEditor(user)
Добавляет данного пользователя в список редакторов Spreadsheet
. Если пользователь уже был в списке зрителей, этот метод продвигает пользователя из списка зрителей.
Параметры
Имя | Тип | Описание |
---|---|---|
user | User | Представление пользователя для добавления. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addEditors(emailAddresses)
Добавляет заданный массив пользователей в список редакторов Spreadsheet
. Если кто-то из пользователей уже был в списке зрителей, этот метод продвигает их из списка зрителей.
Параметры
Имя | Тип | Описание |
---|---|---|
emailAddresses | String[] | Массив адресов электронной почты пользователей для добавления. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addMenu(name, subMenus)
Создает новое меню в пользовательском интерфейсе электронных таблиц.
Каждый пункт меню запускает пользовательскую функцию. Обычно вы хотите вызвать его из функции onOpen()
, чтобы меню автоматически создавалось при загрузке электронной таблицы.
// The onOpen function is executed automatically every time a Spreadsheet is loaded function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = []; // When the user clicks on "addMenuExample" then "Menu Entry 1", the function function1 is // executed. menuEntries.push({name: "Menu Entry 1", functionName: "function1"}); menuEntries.push(null); // line separator menuEntries.push({name: "Menu Entry 2", functionName: "function2"}); ss.addMenu("addMenuExample", menuEntries); }
Параметры
Имя | Тип | Описание |
---|---|---|
name | String | Имя создаваемого меню. |
subMenus | Object[] | Массив карт JavaScript с параметрами name и functionName . Вы можете использовать функции из включенных библиотек, таких как Library.libFunction1 . |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addViewer(emailAddress)
Добавляет данного пользователя в список зрителей Spreadsheet
. Если пользователь уже был в списке редакторов, этот метод не действует.
Параметры
Имя | Тип | Описание |
---|---|---|
emailAddress | String | Адрес электронной почты добавляемого пользователя. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addViewer(user)
Добавляет данного пользователя в список зрителей Spreadsheet
. Если пользователь уже был в списке редакторов, этот метод не действует.
Параметры
Имя | Тип | Описание |
---|---|---|
user | User | Представление пользователя для добавления. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
addViewers(emailAddresses)
Добавляет указанный массив пользователей в список зрителей Spreadsheet
. Если кто-то из пользователей уже был в списке редакторов, для них этот метод не действует.
Параметры
Имя | Тип | Описание |
---|---|---|
emailAddresses | String[] | Массив адресов электронной почты пользователей для добавления. |
Возвращаться
Spreadsheet
— это Spreadsheet
для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
appendRow(rowContents)
Добавляет строку в конец текущей области данных на листе.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Appends a new row with 3 columns to the bottom of the current // data region in the sheet containing the values in the array. sheet.appendRow(["a man", "a plan", "panama"]);
Параметры
Имя | Тип | Описание |
---|---|---|
rowContents | Object[] | Массив значений для вставки после последней строки на листе. |
Возвращаться
Sheet
— Лист, полезный для цепочки методов.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
autoResizeColumn(columnPosition)
Устанавливает ширину данного столбца в соответствии с его содержимым.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; sheet.getRange('a1').setValue('Whenever it is a damp, drizzly November in my soul...'); // Sets the first column to a width which fits the text sheet.autoResizeColumn(1);
Параметры
Имя | Тип | Описание |
---|---|---|
columnPosition | Integer | Позиция данного столбца для изменения размера. |
Возвращаться
Sheet
— лист, полезный для цепочки методов
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
copy(name)
Копирует электронную таблицу и возвращает новую.
// This code makes a copy of the current spreadsheet and names it appropriately var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.copy("Copy of " + ss.getName());
Параметры
Имя | Тип | Описание |
---|---|---|
name | String | Имя копии. |
Возвращаться
Spreadsheet
— Эта электронная таблица для цепочки.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
createDeveloperMetadataFinder()
Возвращает DeveloperMetadataFinder
для поиска метаданных разработчика в рамках этой электронной таблицы. По умолчанию учитываются все метаданные, связанные с электронной таблицей, листами, строками и столбцами.
Возвращаться
DeveloperMetadataFinder
— средство поиска метаданных разработчика для поиска метаданных в рамках этой электронной таблицы.
createTextFinder(findText)
Создает средство поиска текста для электронной таблицы, которое можно использовать для поиска и замены текста в электронной таблице. Поиск начинается с первого листа электронной таблицы.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Creates a text finder. var textFinder = spreadsheet.createTextFinder('dog'); // Returns the first occurrence of 'dog' in the spreadsheet. 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
для электронной таблицы.
deleteActiveSheet()
Удаляет текущий активный лист.
// The code below deletes the currently active sheet and stores the new active sheet in a // variable var newSheet = SpreadsheetApp.getActiveSpreadsheet().deleteActiveSheet();
Возвращаться
Sheet
— новый активный лист.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
deleteColumn(columnPosition)
Удаляет столбец в заданной позиции столбца.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Columns start at "1" - this deletes the first column sheet.deleteColumn(1);
Параметры
Имя | Тип | Описание |
---|---|---|
columnPosition | Integer | Позиция столбца, начиная с 1 для первого столбца. |
Возвращаться
Sheet
— лист, полезный для цепочки методов
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
deleteColumns(columnPosition, howMany)
Удаляет ряд столбцов, начиная с данной позиции столбца.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Columns start at "1" - this deletes the first two columns sheet.deleteColumns(1, 2);
Параметры
Имя | Тип | Описание |
---|---|---|
columnPosition | Integer | Позиция первого удаляемого столбца. |
howMany | Integer | Количество столбцов для удаления. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
deleteRow(rowPosition)
Удаляет строку в заданной позиции строки.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Rows start at "1" - this deletes the first row sheet.deleteRow(1);
Параметры
Имя | Тип | Описание |
---|---|---|
rowPosition | Integer | Позиция строки, начиная с 1 для первой строки. |
Возвращаться
Sheet
— лист, полезный для цепочки методов
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
deleteRows(rowPosition, howMany)
Удаляет ряд строк, начиная с заданной позиции строки.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Rows start at "1" - this deletes the first two rows sheet.deleteRows(1, 2);
Параметры
Имя | Тип | Описание |
---|---|---|
rowPosition | Integer | Позиция первой удаляемой строки. |
howMany | Integer | Количество строк для удаления. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
deleteSheet(sheet)
Удаляет указанный лист.
// The code below deletes the specified sheet. var ss = SpreadsheetApp.getActive(); var sheet = ss.getSheetByName('My Sheet'); ss.deleteSheet(sheet);
Параметры
Имя | Тип | Описание |
---|---|---|
sheet | Sheet | Лист для удаления. |
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
duplicateActiveSheet()
Дублирует активный лист и делает его активным листом.
// The code below makes a duplicate of the active sheet SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
Возвращаться
Sheet
— новый лист.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getActiveCell()
Возвращает активную ячейку на этом листе.
Примечание. Предпочтительно использовать getCurrentCell()
, который возвращает текущую выделенную ячейку.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Returns the active cell var cell = sheet.getActiveCell();
Возвращаться
Range
— текущая активная ячейка
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getActiveRange()
Возвращает выбранный диапазон на активном листе или null
, если активного диапазона нет. Если выбрано несколько диапазонов, этот метод возвращает только последний выбранный диапазон.
Термин «активный диапазон» относится к диапазону, выбранному пользователем на активном листе, но в пользовательской функции он относится к активно пересчитываемой ячейке.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var activeRange = sheet.getActiveRange();
Возвращаться
Range
— активный диапазон
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
Смотрите также
getActiveRangeList()
Возвращает список активных диапазонов на активном листе или null
, если активных диапазонов нет.
Если выбран один диапазон, это ведет себя как вызов getActiveRange()
.
var sheet = SpreadsheetApp.getActiveSheet(); // Returns the list of active ranges. var activeRangeList = sheet.getActiveRangeList();
Возвращаться
RangeList
— список активных диапазонов
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
Смотрите также
getActiveSheet()
Получает активный лист электронной таблицы.
Активный лист электронной таблицы — это лист, отображаемый в пользовательском интерфейсе электронной таблицы.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
Возвращаться
Sheet
— активный лист электронной таблицы.
getAs(contentType)
Верните данные внутри этого объекта в виде большого двоичного объекта, преобразованного в указанный тип контента. Этот метод добавляет к имени файла соответствующее расширение, например, «myfile.pdf». Однако предполагается, что часть имени файла, которая следует за последней точкой (если она есть), является существующим расширением, которое следует заменить. Следовательно, «Список покупок.12.25.2014» становится «Список покупок.12.25.pdf».
Чтобы просмотреть дневные квоты на конверсии, см. Квоты для сервисов Google . На вновь созданные домены Google Workspace могут временно распространяться более строгие квоты.
Параметры
Имя | Тип | Описание |
---|---|---|
contentType | String | Тип MIME для преобразования. Для большинства BLOB-объектов единственным допустимым вариантом является 'application/pdf' . Для изображений в формате BMP, GIF, JPEG или PNG допустимо любое из значений 'image/bmp' , 'image/gif' , 'image/jpeg' или 'image/png' . |
Возвращаться
Blob
— данные в виде большого двоичного объекта.
getBandings()
Возвращает все полосы в этой электронной таблице.
Возвращаться
Banding[]
— полосы в этой электронной таблице.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getBlob()
Верните данные внутри этого объекта в виде большого двоичного объекта.
Возвращаться
Blob
— данные в виде большого двоичного объекта.
getColumnWidth(columnPosition)
Получает ширину в пикселях данного столбца.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Columns start at 1 Logger.log(sheet.getColumnWidth(1));
Параметры
Имя | Тип | Описание |
---|---|---|
columnPosition | Integer | Положение столбца для проверки. |
Возвращаться
Integer
— ширина столбца в пикселях
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getCurrentCell()
Возвращает текущую ячейку на активном листе или null
, если текущей ячейки нет. Текущая ячейка — это ячейка, которая находится в фокусе пользовательского интерфейса Google Таблиц и выделена темной рамкой. Никогда не существует более одной текущей ячейки. Когда пользователь выбирает один или несколько диапазонов ячеек, одна из выбранных ячеек является текущей ячейкой.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Returns the current highlighted cell in the one of the active ranges. var currentCell = sheet.getCurrentCell();
Возвращаться
Range
— текущая ячейка
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataRange()
Возвращает Range
, соответствующий измерениям, в которых присутствуют данные.
Функционально это эквивалентно созданию диапазона, ограниченного A1 и (Sheet.getLastColumn(), Sheet.getLastRow()).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This represents ALL the data var range = sheet.getDataRange(); var values = range.getValues(); // This logs the spreadsheet in CSV format with a trailing comma for (var i = 0; i < values.length; i++) { var row = ""; for (var j = 0; j < values[i].length; j++) { if (values[i][j]) { row = row + values[i][j]; } row = row + ","; } Logger.log(row); }
Возвращаться
Range
— диапазон, состоящий из всех данных в электронной таблице.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSourceFormulas()
Получает все формулы источника данных.
Возвращаться
DataSourceFormula[]
— Список формул источника данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSourcePivotTables()
Получает все сводные таблицы источников данных.
Возвращаться
DataSourcePivotTable[]
— список сводных таблиц источников данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSourceRefreshSchedules()
Получает расписания обновления этой электронной таблицы.
Возвращаться
DataSourceRefreshSchedule[]
— расписания обновления этой электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSourceSheets()
Возвращает все листы источника данных в электронной таблице.
Возвращаться
DataSourceSheet[]
— Массив всех листов источников данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSourceTables()
Получает все таблицы источников данных.
Возвращаться
DataSourceTable[]
— Список таблиц источников данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDataSources()
Возвращает все источники данных в электронной таблице.
Возвращаться
DataSource[]
— Массив всех источников данных.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getDeveloperMetadata()
Получите метаданные разработчика, связанные с электронной таблицей верхнего уровня.
Возвращаться
DeveloperMetadata[]
— метаданные разработчика, связанные с этим диапазоном.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getEditors()
Получает список редакторов для этой Spreadsheet
.
Возвращаться
User[]
— Массив пользователей с правами редактирования.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getFormUrl()
Возвращает URL-адрес формы, которая отправляет свои ответы в эту электронную таблицу, или null
если эта электронная таблица не имеет связанной формы. Если несколько форм отправляют ответы на эту электронную таблицу, возвращаемый URL-адрес формы не определен. В качестве альтернативы, ассоциации URL-адресов формы листа можно получить с помощью метода Sheet.getFormUrl()
.
Возвращаться
String
— URL-адрес формы, которая помещает свои ответы в эту электронную таблицу, или null
если эта электронная таблица не имеет связанной формы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getFrozenColumns()
Возвращает количество замороженных столбцов.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; Logger.log("Number of frozen columns: %s", sheet.getFrozenColumns());
Возвращаться
Integer
— количество замороженных столбцов
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getFrozenRows()
Возвращает количество замороженных строк.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; Logger.log("Number of frozen rows: %s", sheet.getFrozenRows());
Возвращаться
Integer
— количество замороженных строк
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getId()
Получает уникальный идентификатор для этой электронной таблицы. Идентификатор электронной таблицы можно извлечь из ее URL-адреса. Например, идентификатор электронной таблицы в URL-адресе https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 — «abc1234567».
// The code below logs the ID for the active spreadsheet. Logger.log(SpreadsheetApp.getActiveSpreadsheet().getId());
Возвращаться
String
— уникальный идентификатор (или ключ) электронной таблицы.
getImages()
Возвращает все изображения поверх сетки на листе.
Возвращаться
OverGridImage[]
— Массив изображений над сеткой.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getIterativeCalculationConvergenceThreshold()
Возвращает пороговое значение, используемое во время итеративного вычисления. Когда результаты последовательного расчета отличаются менее чем на это значение, итерационный расчет останавливается.
Возвращаться
Number
— Порог сходимости.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getLastColumn()
Возвращает позицию последнего столбца с содержимым.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This logs the value in the very last cell of this sheet var lastRow = sheet.getLastRow(); var lastColumn = sheet.getLastColumn(); var lastCell = sheet.getRange(lastRow, lastColumn); Logger.log(lastCell.getValue());
Возвращаться
Integer
— последний столбец листа, содержащий содержимое.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getLastRow()
Возвращает позицию последней строки с содержимым.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This logs the value in the very last cell of this sheet var lastRow = sheet.getLastRow(); var lastColumn = sheet.getLastColumn(); var lastCell = sheet.getRange(lastRow, lastColumn); Logger.log(lastCell.getValue());
Возвращаться
Integer
— последняя строка листа, содержащая содержимое
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getMaxIterativeCalculationCycles()
Возвращает максимальное количество итераций для использования во время итеративного вычисления.
Возвращаться
Integer
— Максимальное количество итераций вычисления.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getName()
Получает имя документа.
var ss = SpreadsheetApp.getActiveSpreadsheet(); Logger.log(ss.getName());
Возвращаться
String
— имя электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getNamedRanges()
Получает все именованные диапазоны в этой электронной таблице.
// The code below logs the name of the first named range. var namedRanges = SpreadsheetApp.getActiveSpreadsheet().getNamedRanges(); for (var i = 0; i < namedRanges.length; i++) { Logger.log(namedRanges[i].getName()); }
Возвращаться
NamedRange[]
— Массив всех именованных диапазонов в электронной таблице.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getNumSheets()
Возвращает количество листов в этой электронной таблице.
// The code below logs the number of sheets in the active spreadsheet. Logger.log(SpreadsheetApp.getActiveSpreadsheet().getNumSheets());
Возвращаться
Integer
— количество листов в электронной таблице.
getOwner()
Возвращает владельца документа или null
для документа на общем диске.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var owner = ss.getOwner(); Logger.log(owner.getEmail());
Возвращаться
User
— владелец документа или null
, если документ находится на общем диске.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getPredefinedSpreadsheetThemes()
Возвращает список предопределенных тем.
// The code below returns the list of predefined themes. var predefinedThemesList = SpreadsheetApp.getActiveSpreadsheet() .getPredefinedSpreadsheetThemes();
Возвращаться
SpreadsheetTheme[]
— Список предопределенных тем.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getProtections(type)
Получает массив объектов, представляющих все защищенные диапазоны или листы в электронной таблице.
// Remove all range protections in the spreadsheet that the user has permission to edit. var ss = SpreadsheetApp.getActive(); var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE); for (var i = 0; i < protections.length; i++) { var protection = protections[i]; if (protection.canEdit()) { protection.remove(); } }
// Remove all sheet protections in the spreadsheet that the user has permission to edit. var ss = SpreadsheetApp.getActive(); var protections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET); for (var i = 0; i < protections.length; i++) { var protection = protections[i]; if (protection.canEdit()) { protection.remove(); } }
Параметры
Имя | Тип | Описание |
---|---|---|
type | ProtectionType | Тип защищенной области: SpreadsheetApp.ProtectionType.RANGE или SpreadsheetApp.ProtectionType.SHEET . |
Возвращаться
Protection[]
— Массив объектов, представляющих все защищенные диапазоны или листы в электронной таблице.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getRange(a1Notation)
Возвращает диапазон, указанный в нотации A1 или нотации R1C1.
// Get a range A1:D4 on sheet titled "Invoices" var ss = SpreadsheetApp.getActiveSpreadsheet(); var range = ss.getRange("Invoices!A1:D4"); // Get cell A1 on the first sheet var sheet = ss.getSheets()[0]; var cell = sheet.getRange("A1");
Параметры
Имя | Тип | Описание |
---|---|---|
a1Notation | String | Возвращаемый диапазон, указанный в нотации A1 или нотации R1C1. |
Возвращаться
Range
— диапазон в указанном месте
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getRangeByName(name)
Возвращает именованный диапазон или null
, если диапазон с заданным именем не найден. Если несколько листов электронной таблицы используют одно и то же имя диапазона, укажите имя листа без дополнительных кавычек, например, getRangeByName('TaxRates')
или getRangeByName('Sheet Name!TaxRates')
, но не getRangeByName('"Sheet Name"!TaxRates')
.
// Log the number of columns for the range named 'TaxRates' in the active spreadsheet. var range = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('TaxRates'); if (range != null) { Logger.log(range.getNumColumns()); }
Параметры
Имя | Тип | Описание |
---|---|---|
name | String | Имя диапазона, который необходимо получить. |
Возвращаться
Range
— диапазон ячеек с заданным именем.
getRangeList(a1Notations)
Возвращает коллекцию RangeList
, представляющую диапазоны на одном листе, указанном непустым списком нотаций A1 или R1C1.
// Get a list of ranges A1:D4, F1:H4. var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var rangeList = sheet.getRangeList(['A1:D4', 'F1:H4']);
Параметры
Имя | Тип | Описание |
---|---|---|
a1Notations | String[] | Список возвращаемых диапазонов, как указано в нотации A1 или нотации R1C1. |
Возвращаться
RangeList
— список диапазонов в указанном месте
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getRecalculationInterval()
Возвращает интервал расчета для этой электронной таблицы.
Возвращаться
RecalculationInterval
— интервал расчета для этой электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getRowHeight(rowPosition)
Получает высоту в пикселях данной строки.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Rows start at 1 Logger.log(sheet.getRowHeight(1));
Параметры
Имя | Тип | Описание |
---|---|---|
rowPosition | Integer | Позиция строки для проверки. |
Возвращаться
Integer
— высота строки в пикселях
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSelection()
Возвращает текущий Selection
в электронной таблице.
var selection = SpreadsheetApp.getActiveSpreadsheet().getSelection(); var currentCell = selection.getCurrentCell();
Возвращаться
Selection
— текущий выбор
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSheetByName(name)
Возвращает лист с заданным именем.
Если несколько листов имеют одинаковое имя, возвращается самый левый. Возвращает null
если нет листа с заданным именем.
// The code below logs the index of a sheet named "Expenses" var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expenses"); if (sheet != null) { Logger.log(sheet.getIndex()); }
Параметры
Имя | Тип | Описание |
---|---|---|
name | String | Имя листа, который необходимо получить. |
Возвращаться
Sheet
— Лист с заданным именем.
getSheetId()
Возвращает идентификатор листа, представленного этим объектом.
Это идентификатор листа, уникальный для электронной таблицы. Идентификатор представляет собой монотонно возрастающее целое число, назначаемое во время создания листа, которое не зависит от положения листа. Это полезно в сочетании с такими методами, как Range.copyFormatToRange(gridId, column, columnEnd, row, rowEnd)
, которые принимают параметр gridId
, а не экземпляр Sheet
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; Logger.log(sheet.getSheetId());
Возвращаться
Integer
— идентификатор листа, уникальный для электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSheetName()
Возвращает имя листа.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; Logger.log(sheet.getSheetName());
Возвращаться
String
— имя листа
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSheetValues(startRow, startColumn, numRows, numColumns)
Возвращает прямоугольную сетку значений для этого диапазона, начиная с заданных координат. Значение -1, указанное в качестве позиции строки или столбца, эквивалентно получению самой последней строки или столбца, содержащих данные на листе.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // The two samples below produce the same output var values = sheet.getSheetValues(1, 1, 3, 3); Logger.log(values); var range = sheet.getRange(1, 1, 3, 3); values = range.getValues(); Logger.log(values);
Параметры
Имя | Тип | Описание |
---|---|---|
startRow | Integer | Положение стартового ряда. |
startColumn | Integer | Положение начального столбца. |
numRows | Integer | Количество строк, для которых возвращаются значения. |
numColumns | Integer | Количество столбцов, для которых возвращаются значения. |
Возвращаться
Object[][]
— двумерный массив значений
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSheets()
Получает все листы в этой электронной таблице.
// The code below logs the name of the second sheet var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(); if (sheets.length > 1) { Logger.log(sheets[1].getName()); }
Возвращаться
Sheet[]
— Массив всех листов электронной таблицы.
getSpreadsheetLocale()
Получает языковой стандарт электронной таблицы.
Возвращаться
String
— языковой стандарт электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSpreadsheetTheme()
Возвращает текущую тему электронной таблицы или null
, если тема не применена.
// The code below returns the current theme of the spreadsheet. var currentTheme = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTheme();
Возвращаться
SpreadsheetTheme
— Текущая примененная тема.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getSpreadsheetTimeZone()
Получает часовой пояс для электронной таблицы.
Возвращаться
String
— часовой пояс, указанный в «длинном» формате (например, «Америка/Нью-Йорк», как указано на Joda.org ).
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getUrl()
Возвращает URL для данной электронной таблицы.
var ss = SpreadsheetApp.getActiveSpreadsheet(); Logger.log(ss.getUrl());
Возвращаться
String
— URL-адрес данной электронной таблицы.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
getViewers()
Получает список зрителей и комментаторов для этой Spreadsheet
.
Возвращаться
User[]
— Массив пользователей с правами просмотра или комментирования.
Авторизация
Сценарии, использующие этот метод, требуют авторизации в одной или нескольких следующих областях :
-
https://www.googleapis.com/auth/spreadsheets.currentonly
-
https://www.googleapis.com/auth/spreadsheets
hideColumn(column)
Скрывает столбец или столбцы в заданном диапазоне.
let ss = SpreadsheetApp.getActiveSpreadsheet(); let sheet = ss.getSheets()[0]; // This hides the first column let range = sheet.getRange("A1"); sheet.hideColumn(range); // This hides the first 3 columns let range = sheet.getRange("A:C"); sheet.hideColumn(range);
Параметры
Имя | Тип | Описание |
---|---|---|
column | Range | Диапазон столбцов, который нужно скрыть. |
Авторизация
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
hideRow(row)
Hides the rows in the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This hides the first row var range = sheet.getRange("A1"); sheet.hideRow(range);
Parameters
Name | Type | Description |
---|---|---|
row | Range | The row range to hide. |
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
insertColumnAfter(afterPosition)
Inserts a column after the given column position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts a column after the first column position sheet.insertColumnAfter(1);
Parameters
Name | Type | Description |
---|---|---|
afterPosition | Integer | The column after which the new column should be added. |
Return
Sheet
— the sheet, useful for method 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
insertColumnBefore(beforePosition)
Inserts a column before the given column position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts a column in the first column position sheet.insertColumnBefore(1);
Parameters
Name | Type | Description |
---|---|---|
beforePosition | Integer | The column before which the new column should be added. |
Return
Sheet
— the sheet, useful for method 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
insertColumnsAfter(afterPosition, howMany)
Inserts a number of columns after the given column position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts a column in the second column position sheet.insertColumnsAfter(1);
Parameters
Name | Type | Description |
---|---|---|
afterPosition | Integer | The column after which the new column should be added. |
howMany | Integer | The number of columns to insert. |
Return
Sheet
— the sheet, useful for method 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
insertColumnsBefore(beforePosition, howMany)
Inserts a number of columns before the given column position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts five columns before the first column sheet.insertColumnsBefore(1, 5);
Parameters
Name | Type | Description |
---|---|---|
beforePosition | Integer | The column before which the new column should be added. |
howMany | Integer | The number of columns to insert. |
Return
Sheet
— the sheet, useful for method 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
insertDataSourceSheet(spec)
Inserts a new DataSourceSheet
in the spreadsheet and starts data execution. As a side effect, this also makes the new sheet the active sheet.
Throws an exception if the data source type is not enabled. Use SpreadsheetApp#enable...Execution()
methods to enable data execution for specific data source type.
Parameters
Name | Type | Description |
---|---|---|
spec | DataSourceSpec | The data source specification to insert with. |
Return
DataSourceSheet
— The new data source 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
insertImage(blobSource, column, row)
Inserts a Spreadsheet
as an image in the document at a given row and column. The image size is retrieved from the blob contents. The maximum supported blob size is 2MB.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName'); sheet.insertImage(blob, 1, 1);
Parameters
Name | Type | Description |
---|---|---|
blobSource | BlobSource | The blob containing the image contents, MIME type, and (optionally) name. |
column | Integer | The column position. |
row | Integer | The row position. |
Return
OverGridImage
— The inserted image.
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
insertImage(blobSource, column, row, offsetX, offsetY)
Inserts a Spreadsheet
as an image in the document at a given row and column, with a pixel offset. The image size is retrieved from the blob contents. The maximum supported blob size is 2MB.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName'); sheet.insertImage(blob, 1, 1, 10, 10);
Parameters
Name | Type | Description |
---|---|---|
blobSource | BlobSource | The blob containing the image contents, MIME type, and (optionally) name. |
column | Integer | The column position. |
row | Integer | The row position. |
offsetX | Integer | The horizontal offset from cell corner in pixels. |
offsetY | Integer | The vertical offset from cell corner in pixels. |
Return
OverGridImage
— The inserted image.
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
insertImage(url, column, row)
Inserts an image in the document at a given row and column.
The provided URL must be publicly accessible.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; sheet.insertImage("https://www.google.com/images/srpr/logo3w.png", 1, 1);
Parameters
Name | Type | Description |
---|---|---|
url | String | The URL of the image. |
column | Integer | The grid column position. |
row | Integer | The grid row position. |
Return
OverGridImage
— The inserted image.
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
insertImage(url, column, row, offsetX, offsetY)
Inserts an image in the document at a given row and column, with a pixel offset.
The provided URL must be publicly accessible.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; sheet.insertImage("https://www.google.com/images/srpr/logo3w.png", 1, 1, 10, 10);
Parameters
Name | Type | Description |
---|---|---|
url | String | The URL for the image. |
column | Integer | The column position. |
row | Integer | The row position. |
offsetX | Integer | The horizontal offset from cell corner in pixels. |
offsetY | Integer | The vertical offset from cell corner in pixels. |
Return
OverGridImage
— The Inserted image.
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
insertRowAfter(afterPosition)
Inserts a row after the given row position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts a row after the first row position sheet.insertRowAfter(1);
Parameters
Name | Type | Description |
---|---|---|
afterPosition | Integer | The row after which the new row should be added. |
Return
Sheet
— the sheet, useful for method 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
insertRowBefore(beforePosition)
Inserts a row before the given row position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts a row before the first row position sheet.insertRowBefore(1);
Parameters
Name | Type | Description |
---|---|---|
beforePosition | Integer | The row before which the new row should be added. |
Return
Sheet
— the sheet, useful for method 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
insertRowsAfter(afterPosition, howMany)
Inserts a number of rows after the given row position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts five rows after the first row sheet.insertRowsAfter(1, 5);
Parameters
Name | Type | Description |
---|---|---|
afterPosition | Integer | The row after which the new rows should be added. |
howMany | Integer | The number of rows to insert. |
Return
Sheet
— the sheet, useful for method 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
insertRowsBefore(beforePosition, howMany)
Inserts a number of rows before the given row position.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This inserts five rows before the first row sheet.insertRowsBefore(1, 5);
Parameters
Name | Type | Description |
---|---|---|
beforePosition | Integer | The row before which the new rows should be added. |
howMany | Integer | The number of rows to insert. |
Return
Sheet
— the sheet, useful for method 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
insertSheet()
Inserts a new sheet into the spreadsheet, using a default sheet name. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.insertSheet();
Return
Sheet
— The new 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
insertSheet(sheetIndex)
Inserts a new sheet into the spreadsheet at the given index. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.insertSheet(1);
Parameters
Name | Type | Description |
---|---|---|
sheetIndex | Integer | The index of the newly created sheet. To insert a sheet as the first one in the spreadsheet, set it to 0. |
Return
Sheet
— The new 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
insertSheet(sheetIndex, options)
Inserts a new sheet into the spreadsheet at the given index and uses optional advanced arguments. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var templateSheet = ss.getSheetByName('Sales'); ss.insertSheet(1, {template: templateSheet});
Parameters
Name | Type | Description |
---|---|---|
sheetIndex | Integer | The index of the newly created sheet. To insert a sheet as the first one in the spreadsheet, set it to 0. |
options | Object | Optional JavaScript advanced arguments. |
Advanced parameters
Name | Type | Description |
---|---|---|
template | Sheet | All data from the template sheet object is copied to the new sheet. The sheet template must be one of the sheets of the Spreadsheet object. |
Return
Sheet
— The new 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
insertSheet(options)
Inserts a new sheet into the spreadsheet, using a default sheet name and optional advanced arguments. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var templateSheet = ss.getSheetByName('Sales'); ss.insertSheet({template: templateSheet});
Parameters
Name | Type | Description |
---|---|---|
options | Object | Optional JavaScript advanced arguments, listed below. |
Advanced parameters
Name | Type | Description |
---|---|---|
template | Sheet | All data from the template sheet object is copied to the new sheet. The sheet template must be one of the sheets of this Spreadsheet object. |
Return
Sheet
— The new 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
insertSheet(sheetName)
Inserts a new sheet into the spreadsheet with the given name. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.insertSheet('My New Sheet');
Parameters
Name | Type | Description |
---|---|---|
sheetName | String | The name of the new sheet. |
Return
Sheet
— The new 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
insertSheet(sheetName, sheetIndex)
Inserts a new sheet into the spreadsheet with the given name at the given index. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.insertSheet('My New Sheet', 1);
Parameters
Name | Type | Description |
---|---|---|
sheetName | String | The name of the new sheet. |
sheetIndex | Integer | The index of the newly created sheet. To insert a sheet as the first one in the spreadsheet, set it to 0. |
Return
Sheet
— The new 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
insertSheet(sheetName, sheetIndex, options)
Inserts a new sheet into the spreadsheet with the given name at the given index and uses optional advanced arguments. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var templateSheet = ss.getSheetByName('Sales'); ss.insertSheet('My New Sheet', 1, {template: templateSheet});
Parameters
Name | Type | Description |
---|---|---|
sheetName | String | The name of the new sheet. |
sheetIndex | Integer | The index of the newly inserted sheet. To insert a sheet as the first one in a spreadsheet, set it to 0. |
options | Object | Optional JavaScript advanced arguments. |
Advanced parameters
Name | Type | Description |
---|---|---|
template | Sheet | All data from the template sheet object is copied to the new sheet. The sheet template must be one of the sheets of the Spreadsheet object. |
Return
Sheet
— The new 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
insertSheet(sheetName, options)
Inserts a new sheet into the spreadsheet with the given name and uses optional advanced arguments. The new sheet becomes the active sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var templateSheet = ss.getSheetByName('Sales'); ss.insertSheet('My New Sheet', {template: templateSheet});
Parameters
Name | Type | Description |
---|---|---|
sheetName | String | The name of the new sheet. |
options | Object | Optional JavaScript advanced arguments. |
Advanced parameters
Name | Type | Description |
---|---|---|
template | Sheet | All data from the template sheet object is copied to the new sheet. The sheet template must be one of the sheets of the Spreadsheet object. |
Return
Sheet
— The new 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
insertSheetWithDataSourceTable(spec)
Inserts a new sheet in the spreadsheet, creates a DataSourceTable
spanning the entire sheet with the given data source specification, and starts data execution. As a side effect, makes the new sheet the active sheet.
Throws an exception if the data source type is not enabled. Use SpreadsheetApp#enable...Execution()
methods to enable data execution for specific data source type.
Parameters
Name | Type | Description |
---|---|---|
spec | DataSourceSpec | The data source specification to insert with. |
Return
Sheet
— The new 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
isColumnHiddenByUser(columnPosition)
Returns whether the given column is hidden by the user.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Columns start at 1 Logger.log(sheet.isColumnHiddenByUser(1));
Parameters
Name | Type | Description |
---|---|---|
columnPosition | Integer | The position of the column to examine. |
Return
Boolean
— true
if the column is hidden, 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
isIterativeCalculationEnabled()
Returns whether iterative calculation is enabled in this spreadsheet.
Return
Boolean
— true
if iterative calculation is enabled, 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
isRowHiddenByFilter(rowPosition)
Returns whether the given row is hidden by a filter (not a filter view).
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Rows start at 1 Logger.log(sheet.isRowHiddenByFilter(1));
Parameters
Name | Type | Description |
---|---|---|
rowPosition | Integer | The position of the row to examine. |
Return
Boolean
— true
if the row is hidden, 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
isRowHiddenByUser(rowPosition)
Returns whether the given row is hidden by the user.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Rows start at 1 Logger.log(sheet.isRowHiddenByUser(1));
Parameters
Name | Type | Description |
---|---|---|
rowPosition | Integer | The position of the row to examine. |
Return
Boolean
— true
if the row is hidden, 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
moveActiveSheet(pos)
Moves the active sheet to the given position in the list of sheets. Throws an exception if the position is negative or greater than the number of sheets.
// This example assumes that there are 2 sheets in the current // active spreadsheet: one named "first" in position 1 and another named "second" // in position 2. var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Gets the "first" sheet and activates it. var sheet = spreadsheet.getSheetByName("first").activate(); // Logs 'Current index of sheet: 1' console.log("Current index of sheet: %s", sheet.getIndex()); spreadsheet.moveActiveSheet(2); // Logs 'New index of sheet: 2' console.log("New index of sheet: %s", sheet.getIndex());
Parameters
Name | Type | Description |
---|---|---|
pos | Integer | The 1-index position to move the active sheet to in the list of sheets. |
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
moveChartToObjectSheet(chart)
Creates a new SheetType.OBJECT
sheet and moves the provided chart to it. If the chart is already on its own sheet, that sheet is returned without creating a new one.
var sheet = SpreadsheetApp.getActiveSheet(); var chart = sheet.newChart().setPosition(1, 1, 0, 0).build(); sheet.insertChart(chart); var objectSheet = SpreadsheetApp.getActive().moveChartToObjectSheet(chart);
Parameters
Name | Type | Description |
---|---|---|
chart | EmbeddedChart | The chart to move. |
Return
Sheet
— The sheet that the chart is 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
refreshAllDataSources()
Refreshes all supported data sources and their linked data source objects, skipping invalid data source objects.
Use SpreadsheetApp#enable...Execution()
methods to enable data execution for specific data source type.
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
removeEditor(emailAddress)
Removes the given user from the list of editors for the Spreadsheet
. This method doesn't block users from accessing the Spreadsheet
if they belong to a class of users who have general access—for example, if the Spreadsheet
is shared with the user's entire domain, or if the Spreadsheet
is in a shared drive that the user can access.
For Drive files, this also removes the user from the list of viewers.
Parameters
Name | Type | Description |
---|---|---|
emailAddress | String | The email address of the user to remove. |
Return
Spreadsheet
— This Spreadsheet
, 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
removeEditor(user)
Removes the given user from the list of editors for the Spreadsheet
. This method doesn't block users from accessing the Spreadsheet
if they belong to a class of users who have general access—for example, if the Spreadsheet
is shared with the user's entire domain, or if the Spreadsheet
is in a shared drive that the user can access.
For Drive files, this also removes the user from the list of viewers.
Parameters
Name | Type | Description |
---|---|---|
user | User | A representation of the user to remove. |
Return
Spreadsheet
— This Spreadsheet
, 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
removeMenu(name)
Removes a menu that was added by addMenu(name, subMenus)
. The name
argument should have the same value as the corresponding call to addMenu(name, subMenus)
.
// The onOpen function is executed automatically every time a Spreadsheet is loaded function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.addMenu("badMenu", [{name: "remove bad menu", functionName: "removeBadMenu"}, {name: "foo", functionName: "foo"}]); } function removeBadMenu() { var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.removeMenu("badMenu"); // name must match the name used when added the menu } function foo(){ // Do nothing }
Parameters
Name | Type | Description |
---|---|---|
name | String | The name of the menu to remove. |
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
removeNamedRange(name)
Deletes a named range with the given name. Throws an exception if no range with the given name is found in the spreadsheet.
// The code below creates a new named range "foo", and then remove it. var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.setNamedRange("foo", ss.getActiveRange()); ss.removeNamedRange("foo");
Parameters
Name | Type | Description |
---|---|---|
name | String | The range name. |
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
removeViewer(emailAddress)
Removes the given user from the list of viewers and commenters for the Spreadsheet
. This method has no effect if the user is an editor, not a viewer or commenter. This method also doesn't block users from accessing the Spreadsheet
if they belong to a class of users who have general access—for example, if the Spreadsheet
is shared with the user's entire domain, or if the Spreadsheet
is in a shared drive that the user can access.
For Drive files, this also removes the user from the list of editors.
Parameters
Name | Type | Description |
---|---|---|
emailAddress | String | The email address of the user to remove. |
Return
Spreadsheet
— This Spreadsheet
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
removeViewer(user)
Removes the given user from the list of viewers and commenters for the Spreadsheet
. This method has no effect if the user is an editor, not a viewer. This method also doesn't block users from accessing the Spreadsheet
if they belong to a class of users who have general access—for example, if the Spreadsheet
is shared with the user's entire domain, or if the Spreadsheet
is in a shared drive that the user can access.
For Drive files, this also removes the user from the list of editors.
Parameters
Name | Type | Description |
---|---|---|
user | User | A representation of the user to remove. |
Return
Spreadsheet
— This Spreadsheet
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
rename(newName)
Renames the document.
var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.rename("This is the new name");
Parameters
Name | Type | Description |
---|---|---|
newName | String | The new name for the document. |
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
renameActiveSheet(newName)
Renames the current active sheet to the given new name.
// The code below renames the active sheet to "Hello world" SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Hello world");
Parameters
Name | Type | Description |
---|---|---|
newName | String | The new name for the current active 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
resetSpreadsheetTheme()
Removes the applied theme and sets the default theme on the spreadsheet.
// The code below applies default theme on the spreadsheet. SpreadsheetApp.getActiveSpreadsheet().resetSpreadsheetTheme();
Return
SpreadsheetTheme
— The default theme.
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
setActiveRange(range)
Sets the specified range as the active range
in the active sheet, with the top left cell in the range as the current cell
.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var range = sheet.getRange('A1:D4'); sheet.setActiveRange(range); var selection = sheet.getSelection(); // Current cell: A1 var currentCell = selection.getCurrentCell(); // Active Range: A1:D4 var activeRange = selection.getActiveRange();
Parameters
Name | Type | Description |
---|---|---|
range | Range | The range to set as the active range. |
Return
Range
— the newly active 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
setActiveRangeList(rangeList)
Sets the specified list of ranges as the active ranges
in the active sheet. The last range in the list is set as the active range
.
var sheet = SpreadsheetApp.getActiveSheet(); var rangeList = sheet.getRangeList(['D4', 'B2:C4']); sheet.setActiveRangeList(rangeList); var selection = sheet.getSelection(); // Current cell: B2 var currentCell = selection.getCurrentCell(); // Active range: B2:C4 var activeRange = selection.getActiveRange(); // Active range list: [D4, B2:C4] var activeRangeList = selection.getActiveRangeList();
Parameters
Name | Type | Description |
---|---|---|
rangeList | RangeList | The list of ranges to select. |
Return
RangeList
— the newly selected list of ranges
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
setActiveSelection(range)
Sets the active selection region for this sheet.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("A1:D4"); sheet.setActiveSelection(range);
Parameters
Name | Type | Description |
---|---|---|
range | Range | The range to set as the active selection. |
Return
Range
— the newly active 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
setActiveSelection(a1Notation)
Sets the active selection, as specified in A1 notation or R1C1 notation.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; sheet.setActiveSelection("A1:D4");
Parameters
Name | Type | Description |
---|---|---|
a1Notation | String | The range to set as active, as specified in A1 notation or R1C1 notation. |
Return
Range
— the newly active 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
setActiveSheet(sheet)
Sets the given sheet to be the active sheet in the spreadsheet. The Google Sheets UI displays the chosen sheet unless the sheet belongs to a different spreadsheet.
// The code below makes the first sheet active in the active spreadsheet. var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); spreadsheet.setActiveSheet(spreadsheet.getSheets()[0]);
Parameters
Name | Type | Description |
---|---|---|
sheet | Sheet | The sheet to set as the active sheet. |
Return
Sheet
— The active 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
setActiveSheet(sheet, restoreSelection)
Sets the given sheet to be the active sheet in the spreadsheet, with an option to restore the most recent selection within that sheet. The Google Sheets UI displays the chosen sheet unless the sheet belongs to a different spreadsheet.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var firstSheet = spreadsheet.getSheets()[0]; var secondSheet = spreadsheet.getSheets()[1]; // Set the first sheet as the active sheet and select the range D4:F4. spreadsheet.setActiveSheet(firstSheet).getRange('D4:F4').activate(); // Switch to the second sheet to do some work. spreadsheet.setActiveSheet(secondSheet); // Switch back to first sheet, and restore its selection. spreadsheet.setActiveSheet(firstSheet, true); // The selection of first sheet is restored, and it logs D4:F4 var range = spreadsheet.getActiveSheet().getSelection().getActiveRange(); Logger.log(range.getA1Notation());
Parameters
Name | Type | Description |
---|---|---|
sheet | Sheet | The new active sheet. |
restoreSelection | Boolean | Tf true , the most recent selection of the new active sheet becomes selected again as the new sheet becomes active; if false , the new sheet becomes active without changing the current selection. |
Return
Sheet
— The new active 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
setColumnWidth(columnPosition, width)
Sets the width of the given column in pixels.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Sets the first column to a width of 200 pixels sheet.setColumnWidth(1, 200);
Parameters
Name | Type | Description |
---|---|---|
columnPosition | Integer | The position of the given column to set. |
width | Integer | The width in pixels to set it to. |
Return
Sheet
— the sheet, useful for method 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
setCurrentCell(cell)
Sets the specified cell as the current cell
.
If the specified cell is present in an already selected range, then that range becomes the active range with the cell as the current cell.
If the specified cell is not present in any selected range, then any existing selection is removed and the cell becomes the current cell and the active range.
Note: The specified Range
must consist of one cell, otherwise it throws an exception.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var cell = sheet.getRange('B5'); sheet.setCurrentCell(cell); var selection = sheet.getSelection(); // Current cell: B5 var currentCell = selection.getCurrentCell();
Parameters
Name | Type | Description |
---|---|---|
cell | Range | The cell to set as the current cell. |
Return
Range
— the newly set current 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
setFrozenColumns(columns)
Freezes the given number of columns. If zero, no columns are frozen.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Freezes the first column sheet.setFrozenColumns(1);
Parameters
Name | Type | Description |
---|---|---|
columns | Integer | The number of columns to freeze. |
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
setFrozenRows(rows)
Freezes the given number of rows. If zero, no rows are frozen.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Freezes the first row sheet.setFrozenRows(1);
Parameters
Name | Type | Description |
---|---|---|
rows | Integer | The number of rows to freeze. |
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
setIterativeCalculationConvergenceThreshold(minThreshold)
Sets the minimum threshold value for iterative calculation. When the results of successive calculation differ by less than this value, the iterative calculation stops. This value must be non-negative, and defaults to 0.05.
Parameters
Name | Type | Description |
---|---|---|
minThreshold | Number | The minimum convergence threshold (must be non-negative). |
Return
Spreadsheet
— This spreadsheet, 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
setIterativeCalculationEnabled(isEnabled)
Sets whether iterative calculation is enabled in this spreadsheet. If the maximum number of calculation cycles and convergence threshold have not previously been set when the calculation is enabled, they default to 50 and 0.05 respectively. If either has been set previously, they retain their previous values.
Parameters
Name | Type | Description |
---|---|---|
isEnabled | Boolean | true if iterative calculation should be enabled; false otherwise. |
Return
Spreadsheet
— This spreadsheet, 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
setMaxIterativeCalculationCycles(maxIterations)
Sets the maximum number of calculation iterations that should be performed during iterative calculation. This value must be between 1 and 10,000 (inclusive), and defaults to 50.
Parameters
Name | Type | Description |
---|---|---|
maxIterations | Integer | The maximum number of calculation iterations (between 1 and 10,000). |
Return
Spreadsheet
— This spreadsheet, 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
setNamedRange(name, range)
Names a range.
// The code below creates a new named range "TaxRates" in the active spreadsheet var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.setNamedRange("TaxRates", SpreadsheetApp.getActiveRange());
Parameters
Name | Type | Description |
---|---|---|
name | String | The name to give the range. |
range | Range | The range specification. |
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
setRecalculationInterval(recalculationInterval)
Sets how often this spreadsheet should recalculate.
Parameters
Name | Type | Description |
---|---|---|
recalculationInterval | RecalculationInterval | The new recalculation interval. |
Return
Spreadsheet
— This spreadsheet, 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
setRowHeight(rowPosition, height)
Sets the row height of the given row in pixels. By default, rows grow to fit cell contents. If you want to force rows to a specified height, use Sheet.setRowHeightsForced(startRow, numRows, height)
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Sets the first row to a height of 200 pixels sheet.setRowHeight(1, 200);
Parameters
Name | Type | Description |
---|---|---|
rowPosition | Integer | The row position to change. |
height | Integer | The height in pixels to set it to. |
Return
Sheet
— The sheet, useful for method 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
setSpreadsheetLocale(locale)
Sets the spreadsheet locale.
Parameters
Name | Type | Description |
---|---|---|
locale | String | The locale code to use (for example, 'en', 'fr', or 'en_US'). |
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
setSpreadsheetTheme(theme)
Sets a theme on the spreadsheet.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // The code below sets the second predefined theme as the current theme of the spreadsheet. var predefinedThemesList = spreadsheet.getPredefinedSpreadsheetThemes(); spreadsheet.setSpreadsheetTheme(predefinedThemesList[1]);
Parameters
Name | Type | Description |
---|---|---|
theme | SpreadsheetTheme | The theme to apply. |
Return
SpreadsheetTheme
— The new current theme.
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
setSpreadsheetTimeZone(timezone)
Sets the time zone for the spreadsheet.
Parameters
Name | Type | Description |
---|---|---|
timezone | String | The time zone, specified in "long" format (for example, "America/New_York", as listed by Joda.org ). |
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
show(userInterface)
Displays a custom user interface component in a dialog centered in the user's browser's viewport. The server-side script's execution is not suspended. To communicate with the server side, the user interface component must make asynchronous callbacks to the server-side script.
If the server-side script previously displayed a dialog that has not yet been dismissed, then the existing dialog is replaced with the newly requested dialog's user interface.
The following code snippet displays a simple HtmlService
application in a dialog with the specified title, height, and width:
var htmlApp = HtmlService .createHtmlOutput('<p>A change of speed, a change of style...</p>') .setTitle('My HtmlService Application') .setWidth(250) .setHeight(300); SpreadsheetApp.getActiveSpreadsheet().show(htmlApp); // The script resumes execution immediately after showing the dialog.
Parameters
Name | Type | Description |
---|---|---|
userInterface | Object | An HtmlOutput . |
Authorization
Scripts that use this method require authorization with one or more of the following scopes :
-
https://www.googleapis.com/auth/script.container.ui
sort(columnPosition)
Sorts a sheet by column, ascending.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Sorts the sheet by the first column, ascending sheet.sort(1);
Parameters
Name | Type | Description |
---|---|---|
columnPosition | Integer | The column to sort by. |
Return
Sheet
— the sheet, useful for method 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
sort(columnPosition, ascending)
Sorts a sheet by column. Takes a parameter to specify ascending or descending.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // Sorts the sheet by the first column, descending sheet.sort(1, false);
Parameters
Name | Type | Description |
---|---|---|
columnPosition | Integer | The column to sort by. |
ascending | Boolean | true for ascending sorts, false for descending. |
Return
Sheet
— the sheet, useful for method 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
toast(msg)
Shows a popup window in the lower right corner of the spreadsheet with the given message.
// Show a popup with the message "Task started". SpreadsheetApp.getActiveSpreadsheet().toast('Task started');
Parameters
Name | Type | Description |
---|---|---|
msg | String | The message to be shown in the toast. |
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
toast(msg, title)
Shows a popup window in the lower right corner of the spreadsheet with the given message and title.
// Show a popup with the title "Status" and the message "Task started". SpreadsheetApp.getActiveSpreadsheet().toast('Task started', 'Status');
Parameters
Name | Type | Description |
---|---|---|
msg | String | The message to be shown in the toast. |
title | String | The optional title of the toast. |
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
toast(msg, title, timeoutSeconds)
Shows a popup window in the lower right corner of the spreadsheet with the given title and message, that stays visible for a certain length of time.
// Show a 3-second popup with the title "Status" and the message "Task started". SpreadsheetApp.getActiveSpreadsheet().toast('Task started', 'Status', 3);
Parameters
Name | Type | Description |
---|---|---|
msg | String | The message to be shown in the toast. |
title | String | The optional title of the toast. |
timeoutSeconds | Number | The timeout in seconds; if null , the toast defaults to 5 seconds; if negative, the toast remains until dismissed. |
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
unhideColumn(column)
Unhides the column in the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This unhides the first column if it was previously hidden var range = sheet.getRange("A1"); sheet.unhideColumn(range);
Parameters
Name | Type | Description |
---|---|---|
column | Range | The range to unhide, if hidden. |
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
unhideRow(row)
Unhides the row in the given range.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; // This unhides the first row if it was previously hidden var range = sheet.getRange("A1"); sheet.unhideRow(range);
Parameters
Name | Type | Description |
---|---|---|
row | Range | The range to unhide, if hidden. |
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
updateMenu(name, subMenus)
Updates a menu that was added by addMenu(name, subMenus)
. Works exactly like addMenu(name, subMenus)
.
var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = []; menuEntries.push({name: "Lone Menu Entry", functionName: "function1"}); ss.updateMenu("addMenuExample", menuEntries);
Parameters
Name | Type | Description |
---|---|---|
name | String | The name of the menu to update. |
subMenus | Object[] | An array of JavaScript maps with name and functionName parameters. You can use functions from included libraries, such as Library.libFunction1 . |
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
waitForAllDataExecutionsCompletion(timeoutInSeconds)
Waits until all the current executions in the spreadsheet complete, timing out after the provided number of seconds. Throws an exception if the executions are not completed when timing out, but does not cancel the data executions.
Parameters
Name | Type | Description |
---|---|---|
timeoutInSeconds | Integer | The time to wait for data executions, in seconds. The maximum is 300 seconds. |
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