Class Sheet

Лист

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

Методы

Метод Тип возврата Краткое описание
activate() Sheet Активирует этот лист.
addDeveloperMetadata(key) Sheet Добавляет метаданные разработчика с указанным ключом на лист.
addDeveloperMetadata(key, visibility) Sheet Добавляет метаданные разработчика с указанным ключом и видимостью на лист.
addDeveloperMetadata(key, value) Sheet Добавляет метаданные разработчика с указанным ключом и значением на лист.
addDeveloperMetadata(key, value, visibility) Sheet Добавляет метаданные разработчика с указанным ключом, значением и видимостью на лист.
appendRow(rowContents) Sheet Добавляет строку в конец текущей области данных на листе.
asDataSourceSheet() DataSourceSheet Возвращает лист как DataSourceSheet , если лист имеет тип SheetType.DATASOURCE , или null в противном случае.
autoResizeColumn(columnPosition) Sheet Устанавливает ширину данного столбца в соответствии с его содержимым.
autoResizeColumns(startColumn, numColumns) Sheet Устанавливает ширину всех столбцов, начиная с заданной позиции столбца, в соответствии с их содержимым.
autoResizeRows(startRow, numRows) Sheet Устанавливает высоту всех строк, начиная с заданной позиции строки, в соответствии с их содержимым.
clear() Sheet Очищает лист от содержимого и информации о форматировании.
clear(options) Sheet Очищает оглавление и/или формат, как указано с заданными дополнительными параметрами.
clearConditionalFormatRules() void Удаляет все правила условного форматирования с листа.
clearContents() Sheet Очищает лист содержания, сохраняя при этом информацию о форматировании.
clearFormats() Sheet Очищает лист от форматирования, сохраняя содержимое.
clearNotes() Sheet Очищает лист от всех заметок.
collapseAllColumnGroups() Sheet Сворачивает все группы столбцов на листе.
collapseAllRowGroups() Sheet Сворачивает все группы строк на листе.
copyTo(spreadsheet) Sheet Копирует лист в заданную электронную таблицу, которая может быть той же электронной таблицей, что и источник.
createDeveloperMetadataFinder() DeveloperMetadataFinder Возвращает DeveloperMetadataFinder для поиска метаданных разработчика в рамках этого листа.
createTextFinder(findText) TextFinder Создает средство поиска текста для листа, которое может находить и заменять текст на листе.
deleteColumn(columnPosition) Sheet Удаляет столбец в заданной позиции столбца.
deleteColumns(columnPosition, howMany) void Удаляет ряд столбцов, начиная с данной позиции столбца.
deleteRow(rowPosition) Sheet Удаляет строку в заданной позиции строки.
deleteRows(rowPosition, howMany) void Удаляет ряд строк, начиная с заданной позиции строки.
expandAllColumnGroups() Sheet Разворачивает все группы столбцов на листе.
expandAllRowGroups() Sheet Разворачивает все группы строк на листе.
expandColumnGroupsUpToDepth(groupDepth) Sheet Разворачивает все группы столбцов до заданной глубины и сворачивает все остальные.
expandRowGroupsUpToDepth(groupDepth) Sheet Разворачивает все группы строк до заданной глубины и сворачивает все остальные.
getActiveCell() Range Возвращает активную ячейку на этом листе.
getActiveRange() Range Возвращает выбранный диапазон на активном листе или null , если активного диапазона нет.
getActiveRangeList() RangeList Возвращает список активных диапазонов на активном листе или null , если активных диапазонов нет.
getBandings() Banding[] Возвращает все полосы на этом листе.
getCharts() EmbeddedChart[] Возвращает массив диаграмм на этом листе.
getColumnGroup(columnIndex, groupDepth) Group Возвращает группу столбцов с заданным индексом и глубиной группы.
getColumnGroupControlPosition() GroupControlTogglePosition Возвращает GroupControlTogglePosition для всех групп столбцов на листе.
getColumnGroupDepth(columnIndex) Integer Возвращает глубину группы столбца по заданному индексу.
getColumnWidth(columnPosition) Integer Получает ширину в пикселях данного столбца.
getConditionalFormatRules() ConditionalFormatRule[] Получите все правила условного форматирования на этом листе.
getCurrentCell() Range Возвращает текущую ячейку на активном листе или null , если текущей ячейки нет.
getDataRange() Range Возвращает Range , соответствующий измерениям, в которых присутствуют данные.
getDataSourceFormulas() DataSourceFormula[] Получает все формулы источника данных.
getDataSourcePivotTables() DataSourcePivotTable[] Получает все сводные таблицы источников данных.
getDataSourceTables() DataSourceTable[] Получает все таблицы источников данных.
getDeveloperMetadata() DeveloperMetadata[] Получите все метаданные разработчика, связанные с этим листом.
getDrawings() Drawing[] Возвращает массив рисунков на листе.
getFilter() Filter Возвращает фильтр на этом листе или null , если фильтра нет.
getFormUrl() String Возвращает URL-адрес формы, которая отправляет ответы на этот лист, или null если этот лист не имеет связанной формы.
getFrozenColumns() Integer Возвращает количество замороженных столбцов.
getFrozenRows() Integer Возвращает количество замороженных строк.
getImages() OverGridImage[] Возвращает все изображения поверх сетки на листе.
getIndex() Integer Получает положение листа в его родительской электронной таблице.
getLastColumn() Integer Возвращает позицию последнего столбца с содержимым.
getLastRow() Integer Возвращает позицию последней строки с содержимым.
getMaxColumns() Integer Возвращает текущее количество столбцов на листе независимо от содержимого.
getMaxRows() Integer Возвращает текущее количество строк на листе независимо от содержимого.
getName() String Возвращает имя листа.
getNamedRanges() NamedRange[] Получает все именованные диапазоны на этом листе.
getParent() Spreadsheet Возвращает Spreadsheet , содержащую этот лист.
getPivotTables() PivotTable[] Возвращает все сводные таблицы на этом листе.
getProtections(type) Protection[] Получает массив объектов, представляющих все защищенные диапазоны на листе, или одноэлементный массив, представляющий защиту на самом листе.
getRange(row, column) Range Возвращает диапазон с верхней левой ячейкой по заданным координатам.
getRange(row, column, numRows) Range Возвращает диапазон с верхней левой ячейкой с заданными координатами и с заданным количеством строк.
getRange(row, column, numRows, numColumns) Range Возвращает диапазон с верхней левой ячейкой по заданным координатам с заданным количеством строк и столбцов.
getRange(a1Notation) Range Возвращает диапазон, указанный в нотации A1 или нотации R1C1.
getRangeList(a1Notations) RangeList Возвращает коллекцию RangeList , представляющую диапазоны на одном листе, указанном непустым списком нотаций A1 или R1C1.
getRowGroup(rowIndex, groupDepth) Group Возвращает группу строк с заданным индексом и глубиной группы.
getRowGroupControlPosition() GroupControlTogglePosition Возвращает GroupControlTogglePosition для всех групп строк на листе.
getRowGroupDepth(rowIndex) Integer Возвращает глубину группы строки по заданному индексу.
getRowHeight(rowPosition) Integer Получает высоту в пикселях данной строки.
getSelection() Selection Возвращает текущий Selection в электронной таблице.
getSheetId() Integer Возвращает идентификатор листа, представленного этим объектом.
getSheetName() String Возвращает имя листа.
getSheetValues(startRow, startColumn, numRows, numColumns) Object[][] Возвращает прямоугольную сетку значений для этого диапазона, начиная с заданных координат.
getSlicers() Slicer[] Возвращает массив слайсеров на листе.
getTabColorObject() Color Получает цвет вкладки листа или null , если вкладка листа не имеет цвета.
getType() SheetType Возвращает тип листа.
hasHiddenGridlines() Boolean Возвращает true , если линии сетки листа скрыты; в противном случае возвращает false .
hideColumn(column) void Скрывает столбец или столбцы в заданном диапазоне.
hideColumns(columnIndex) void Скрывает один столбец с заданным индексом.
hideColumns(columnIndex, numColumns) void Скрывает один или несколько последовательных столбцов, начиная с заданного индекса.
hideRow(row) void Скрывает строки в заданном диапазоне.
hideRows(rowIndex) void Скрывает строку по заданному индексу.
hideRows(rowIndex, numRows) void Скрывает одну или несколько последовательных строк, начинающихся с заданного индекса.
hideSheet() Sheet Скрывает этот лист.
insertChart(chart) void Добавляет новую диаграмму на этот лист.
insertColumnAfter(afterPosition) Sheet Вставляет столбец после заданной позиции столбца.
insertColumnBefore(beforePosition) Sheet Вставляет столбец перед заданной позицией столбца.
insertColumns(columnIndex) void Вставляет пустой столбец на лист в указанном месте.
insertColumns(columnIndex, numColumns) void Вставляет один или несколько последовательных пустых столбцов на лист, начиная с указанного места.
insertColumnsAfter(afterPosition, howMany) Sheet Вставляет количество столбцов после заданной позиции столбца.
insertColumnsBefore(beforePosition, howMany) Sheet Вставляет несколько столбцов перед заданной позицией столбца.
insertImage(blobSource, column, row) OverGridImage Вставляет BlobSource как изображение в документ в указанной строке и столбце.
insertImage(blobSource, column, row, offsetX, offsetY) OverGridImage Вставляет BlobSource как изображение в документ в указанной строке и столбце со смещением в пикселях.
insertImage(url, column, row) OverGridImage Вставляет изображение в документ в заданную строку и столбец.
insertImage(url, column, row, offsetX, offsetY) OverGridImage Вставляет изображение в документ в указанную строку и столбец со смещением в пикселях.
insertRowAfter(afterPosition) Sheet Вставляет строку после заданной позиции строки.
insertRowBefore(beforePosition) Sheet Вставляет строку перед заданной позицией строки.
insertRows(rowIndex) void Вставляет пустую строку в лист в указанном месте.
insertRows(rowIndex, numRows) void Вставляет одну или несколько последовательных пустых строк в лист, начиная с указанного места.
insertRowsAfter(afterPosition, howMany) Sheet Вставляет ряд строк после заданной позиции строки.
insertRowsBefore(beforePosition, howMany) Sheet Вставляет ряд строк перед заданной позицией строки.
insertSlicer(range, anchorRowPos, anchorColPos) Slicer Добавляет новый слайсер на этот лист.
insertSlicer(range, anchorRowPos, anchorColPos, offsetX, offsetY) Slicer Добавляет новый слайсер на этот лист.
isColumnHiddenByUser(columnPosition) Boolean Возвращает, скрыт ли данный столбец пользователем.
isRightToLeft() Boolean Возвращает true , если этот макет листа расположен справа налево.
isRowHiddenByFilter(rowPosition) Boolean Возвращает, скрыта ли данная строка фильтром (не представлением фильтра).
isRowHiddenByUser(rowPosition) Boolean Возвращает, скрыта ли данная строка пользователем.
isSheetHidden() Boolean Возвращает true , если лист в данный момент скрыт.
moveColumns(columnSpec, destinationIndex) void Перемещает столбцы, выбранные заданным диапазоном, в положение, указанное в параметре destinationIndex .
moveRows(rowSpec, destinationIndex) void Перемещает строки, выбранные заданным диапазоном, в положение, указанное в параметре destinationIndex .
newChart() EmbeddedChartBuilder Возвращает построитель для создания новой диаграммы для этого листа.
protect() Protection Создает объект, который может защитить лист от редактирования, кроме пользователей, у которых есть разрешение.
removeChart(chart) void Удаляет диаграмму с родительского листа.
setActiveRange(range) Range Устанавливает указанный диапазон в качестве active range на активном листе, при этом верхняя левая ячейка в диапазоне является current cell .
setActiveRangeList(rangeList) RangeList Задает указанный список диапазонов в качестве active ranges на активном листе.
setActiveSelection(range) Range Устанавливает активную область выбора для этого листа.
setActiveSelection(a1Notation) Range Устанавливает активный выбор, как указано в нотации A1 или нотации R1C1.
setColumnGroupControlPosition(position) Sheet Задает положение переключателя управления группой столбцов на листе.
setColumnWidth(columnPosition, width) Sheet Устанавливает ширину данного столбца в пикселях.
setColumnWidths(startColumn, numColumns, width) Sheet Устанавливает ширину заданных столбцов в пикселях.
setConditionalFormatRules(rules) void Заменяет все существующие на данный момент правила условного форматирования на листе правилами ввода.
setCurrentCell(cell) Range Устанавливает указанную ячейку в качестве current cell .
setFrozenColumns(columns) void Замораживает заданное количество столбцов.
setFrozenRows(rows) void Замораживает заданное количество строк.
setHiddenGridlines(hideGridlines) Sheet Скрывает или показывает линии сетки листа.
setName(name) Sheet Задает имя листа.
setRightToLeft(rightToLeft) Sheet Устанавливает или отменяет макет листа справа налево.
setRowGroupControlPosition(position) Sheet Задает положение переключателя управления группой строк на листе.
setRowHeight(rowPosition, height) Sheet Устанавливает высоту строки данной строки в пикселях.
setRowHeights(startRow, numRows, height) Sheet Устанавливает высоту заданных строк в пикселях.
setRowHeightsForced(startRow, numRows, height) Sheet Устанавливает высоту заданных строк в пикселях.
setTabColor(color) Sheet Задает цвет вкладки листа.
setTabColorObject(color) Sheet Задает цвет вкладки листа.
showColumns(columnIndex) void Отображает столбец с заданным индексом.
showColumns(columnIndex, numColumns) void Отображает один или несколько последовательных столбцов, начиная с заданного индекса.
showRows(rowIndex) void Отображает строку с заданным индексом.
showRows(rowIndex, numRows) void Отображает одну или несколько последовательных строк, начинающихся с заданного индекса.
showSheet() Sheet Делает лист видимым.
sort(columnPosition) Sheet Сортирует лист по столбцу по возрастанию.
sort(columnPosition, ascending) Sheet Сортирует лист по столбцу.
unhideColumn(column) void Отображает столбец в заданном диапазоне.
unhideRow(row) void Отображает строку в заданном диапазоне.
updateChart(chart) void Обновляет диаграмму на этом листе.

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

activate()

Активирует этот лист. Не изменяет сам лист, а только представление родителя об активном листе.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.activate();

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

Sheet — новый активный лист.


addDeveloperMetadata(key)

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

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

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

// Adds the key 'NAME' to the developer metadata for the sheet.
sheet.addDeveloperMetadata('NAME');

// Gets the updated metadata info and logs it to the console.
console.log(sheet.getDeveloperMetadata()[0].getKey());

Параметры

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

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

addDeveloperMetadata(key, visibility)

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

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

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

// Adds the key 'NAME' and sets the developer metadata visibility to PROJECT
// for the sheet.
sheet.addDeveloperMetadata('NAME', SpreadsheetApp.DeveloperMetadataVisibility.PROJECT);

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

Параметры

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

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

addDeveloperMetadata(key, value)

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

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

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

// Adds the key 'COMPANY' with the value 'TECH' to the developer metadata for the sheet.
sheet.addDeveloperMetadata('COMPANY', 'TECH');

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

Параметры

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

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

addDeveloperMetadata(key, value, visibility)

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

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

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

// Adds the key 'COMPANY' with the value 'TECH' to the developer metadata and sets the
// visibility to DOCUMENT for the sheet.
sheet.addDeveloperMetadata(
  'COMPANY',
  'TECH',
  SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);

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

Параметры

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

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

Sheet — Этот лист для цепочки.

Авторизация

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

  • 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

asDataSourceSheet()

Возвращает лист как DataSourceSheet , если лист имеет тип SheetType.DATASOURCE , или null в противном случае.

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

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

// Gets the data source sheet value if the sheet is of type
// SpreadsheetApp.SheetType.DATASOURCE, otherwise this returns a null value.
const dataSourceSheet = sheet.asDataSourceSheet();

// Gets the data source sheet value and logs it to the console.
console.log(dataSourceSheet);
console.log(sheet.getType().toString());

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

DataSourceSheet — Лист источника данных.

Авторизация

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

  • 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

autoResizeColumns(startColumn, numColumns)

Устанавливает ширину всех столбцов, начиная с заданной позиции столбца, в соответствии с их содержимым.

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

// Sets the first 15 columns to a width that fits their text.
sheet.autoResizeColumns(1, 15);

Параметры

Имя Тип Описание
startColumn Integer Начальный столбец для автоматического изменения размера.
numColumns Integer Количество столбцов для автоматического изменения размера.

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

autoResizeRows(startRow, numRows)

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

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

// Sets the first 15 rows to a height that fits their text.
sheet.autoResizeRows(1, 15);

Параметры

Имя Тип Описание
startRow Integer Начальная строка для автоматического изменения размера.
numRows Integer Количество строк для автоматического изменения размера.

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

clear()

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

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.clear();

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

Sheet — очищенный лист.

Авторизация

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

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

clear(options)

Очищает оглавление и/или формат, как указано с заданными дополнительными параметрами.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
sheet.clear({ formatOnly: true, contentsOnly: true });

Параметры

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

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

Имя Тип Описание
contentsOnly Boolean Нужно ли очищать содержимое.
formatOnly Boolean Очищать ли формат.

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

clearConditionalFormatRules()

Удаляет все правила условного форматирования с листа. Эквивалентно вызову setConditionalFormatRules(rules) с пустым массивом в качестве входных данных.

var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearConditionalFormatRules();

Авторизация

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

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

clearContents()

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

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.clearContents();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

clearFormats()

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

Форматирование относится к тому, как данные форматируются в соответствии с вариантами выбора в меню «Формат» (например, полужирный шрифт, курсив, условное форматирование), а не к ширине или высоте ячеек.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.clearFormats();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

clearNotes()

Очищает лист от всех заметок.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.clearNotes();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

collapseAllColumnGroups()

Сворачивает все группы столбцов на листе.

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

// All column groups on the sheet are collapsed.
sheet.collapseAllColumnGroups();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

collapseAllRowGroups()

Сворачивает все группы строк на листе.

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

// All row groups on the sheet are collapsed.
sheet.collapseAllRowGroups();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

copyTo(spreadsheet)

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

var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];

var destination = SpreadsheetApp.openById('ID_GOES HERE');
sheet.copyTo(destination);

Параметры

Имя Тип Описание
spreadsheet Spreadsheet Электронная таблица для копирования этого листа, которая может быть той же электронной таблицей, что и источник.

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

Sheet — новый лист для цепочки.

Авторизация

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

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

createDeveloperMetadataFinder()

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

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

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

// Adds developer metadata for testing.
sheet.addDeveloperMetadata('CITY', 'PARIS');

// Creates the developer metadata finder.
const metadatafinder = sheet.createDeveloperMetadataFinder();

// Finds the metadata with value 'PARIS' and displays its key in the console.
console.log(metadatafinder.withValue('PARIS').find()[0].getKey());

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

DeveloperMetadataFinder — Средство поиска метаданных разработчика для поиска метаданных в рамках этого листа.


createTextFinder(findText)

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

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

// Creates  a text finder.
var textFinder = sheet.createTextFinder('dog');

// Returns the first occurrence of 'dog' in the sheet.
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 Текст для поиска.

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

TextFinderTextFinder для листа.


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

expandAllColumnGroups()

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

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

// All column groups on the sheet are expanded.
sheet.expandAllColumnGroups();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

expandAllRowGroups()

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

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

// All row groups on the sheet are expanded.
sheet.expandAllRowGroups();

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

expandColumnGroupsUpToDepth(groupDepth)

Разворачивает все группы столбцов до заданной глубины и сворачивает все остальные.

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

// All column groups of depth 2 and lower are expanded, and groups with depth
// 3 and higher are collapsed.
sheet.expandColumnGroupsUpToDepth(2);

Параметры

Имя Тип Описание
groupDepth Integer Глубина группы, до которой следует расширить группы столбцов.

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

Sheet — Этот лист для цепочки.

Авторизация

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

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

expandRowGroupsUpToDepth(groupDepth)

Разворачивает все группы строк до заданной глубины и сворачивает все остальные.

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

// All row groups of depth 2 and lower are expanded, and groups with depth
// 3 and higher are collapsed.
sheet.expandRowGroupsUpToDepth(2);

Параметры

Имя Тип Описание
groupDepth Integer Глубина группы, до которой расширяются группы строк.

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

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

Смотрите также


getBandings()

Возвращает все полосы на этом листе.

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

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

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

// Gets info on the bandings' second row color and logs it to the console.
for (const banding of bandings) {
  console.log(banding.getSecondRowColor());
}

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

Banding[] — все полосы на этом листе.

Авторизация

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

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

getCharts()

Возвращает массив диаграмм на этом листе.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var charts = sheet.getCharts();

for (var i in charts) {
  var chart = charts[i];
  // Do something with the chart
}

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

EmbeddedChart[] — Массив диаграмм.

Авторизация

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

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

getColumnGroup(columnIndex, groupDepth)

Возвращает группу столбцов с заданным индексом и глубиной группы.

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

// Returns the group whose control index is at column 2 and has a depth of 1, or
// null if the group doesn’t exist.
var columnGroup = sheet.getColumnGroup(2, 1);

Параметры

Имя Тип Описание
columnIndex Integer Индекс столбца переключателя управления группой или индекс внутри группы.
groupDepth Integer Глубина группы.

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

Group — группа столбцов по контрольному индексу и глубине или создает исключение, если группа не существует.

Авторизация

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

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

getColumnGroupControlPosition()

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

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

// GroupControlTogglePosition.AFTER if the column grouping control toggle is shown after the
// group.
var columnGroupControlPosition = sheet.getColumnGroupControlPosition();

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

GroupControlTogglePositiontrue , если переключатель управления группировкой столбцов отображается после группы на этом листе, и false в противном случае.

Авторизация

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

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

getColumnGroupDepth(columnIndex)

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

Глубина группы указывает, сколько групп пересекается со столбцом. Это может варьироваться от нуля до восьми.

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

// 1 if there is a group over columns 1 through 3
var groupDepth = sheet.getColumnGroupDepth(1);

Параметры

Имя Тип Описание
columnIndex Integer Индекс столбца.

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

Integer — Глубина группы столбца по данному индексу.

Авторизация

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

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

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

getConditionalFormatRules()

Получите все правила условного форматирования на этом листе.

// Logs the conditional format rules in a sheet.
var rules = SpreadsheetApp.getActiveSheet().getConditionalFormatRules();
for (var i = 0; i < rules.length; i++) {
  var rule = rules[i];
  Logger.log(rule);
}

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

ConditionalFormatRule[] — Массив всех правил на листе.

Авторизация

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

  • 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

getDataSourceTables()

Получает все таблицы источников данных.

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

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

Авторизация

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

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

getDeveloperMetadata()

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

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

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

// Adds developer metadata for testing.
sheet.addDeveloperMetadata('CITY', 'PARIS');

// Gets all the developer metadata for the sheet.
const developerMetaDataList = sheet.getDeveloperMetadata();

// Logs the developer metadata to the console.
for (const developerMetaData of developerMetaDataList) {
  console.log(developerMetaData.getKey());
}

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

DeveloperMetadata[] — метаданные разработчика, связанные с этим листом.

Авторизация

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

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

getDrawings()

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

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

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

// Gets all the drawings from the sheet.
const allDrawings = sheet.getDrawings();

 // Logs the number of drawings present on the sheet.
console.log(allDrawings.length);

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

Drawing[] — Список рисунков на этом листе.

Авторизация

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

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

getFilter()

Возвращает фильтр на этом листе или null , если фильтра нет.

// Gets the filter on the active sheet.
let ss = SpreadsheetApp.getActiveSheet();
let filter = ss.getFilter();

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

Filter — Фильтр.

Авторизация

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

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

getFormUrl()

Возвращает URL-адрес формы, которая отправляет ответы на этот лист, или null если этот лист не имеет связанной формы.

var sheet = SpreadsheetApp.getActiveSheet();
var 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

getImages()

Возвращает все изображения поверх сетки на листе.

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

OverGridImage[] — Массив изображений над сеткой.

Авторизация

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

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

getIndex()

Получает положение листа в его родительской электронной таблице. Начинается с 1.

var ss = SpreadsheetApp.getActiveSpreadsheet();
// Note that the JavaScript index is 0, but this logs 1
var sheet = ss.getSheets()[0];
// ... because spreadsheets are 1-indexed
Logger.log(sheet.getIndex());

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

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

Авторизация

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

  • 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

getMaxColumns()

Возвращает текущее количество столбцов на листе независимо от содержимого.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
Logger.log(first.getMaxColumns());

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

Integer — максимальная ширина листа.

Авторизация

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

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

getMaxRows()

Возвращает текущее количество строк на листе независимо от содержимого.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
Logger.log(first.getMaxRows());

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

Integer — Максимальная высота листа.

Авторизация

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

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

getName()

Возвращает имя листа.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
Logger.log(sheet.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.getActiveSheet().getNamedRanges();
if (namedRanges.length > 1) {
  Logger.log(namedRanges[0].getName());
}

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

NamedRange[] — Массив всех именованных диапазонов на листе.

Авторизация

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

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

getParent()

Возвращает Spreadsheet , содержащую этот лист.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// parent is identical to ss
var parent = sheet.getParent();

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

Spreadsheet — родительская электронная таблица.

Авторизация

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

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

getPivotTables()

Возвращает все сводные таблицы на этом листе.

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

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

// Gets all the pivot table info for the sheet.
const pivotTables = sheet.getPivotTables();

// Logs the pivot tables to the console.
for (const pivotTable of pivotTables) {
  console.log(pivotTable.getSourceDataRange().getValues());
}

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

PivotTable[] — сводные таблицы на этом листе.

Авторизация

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

  • 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 sheet = SpreadsheetApp.getActiveSheet();
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}
// Remove sheet protection from the active sheet, if the user has permission to edit it.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0];
if (protection && 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(row, column)

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

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Passing only two arguments returns a "range" with a single cell.
var range = sheet.getRange(1, 1);
var values = range.getValues();
Logger.log(values[0][0]);

Параметры

Имя Тип Описание
row Integer Индекс строки возвращаемой ячейки; индексация строк начинается с 1.
column Integer Индекс столбца возвращаемой ячейки; индексация столбца начинается с 1.

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

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

Авторизация

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

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

getRange(row, column, numRows)

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

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// When the "numRows" argument is used, only a single column of data is returned.
var range = sheet.getRange(1, 1, 3);
var values = range.getValues();

// Prints 3 values from the first column, starting from row 1.
for (var row in values) {
  for (var col in values[row]) {
    Logger.log(values[row][col]);
  }
}

Параметры

Имя Тип Описание
row Integer Начальный индекс строки диапазона; индексация строк начинается с 1.
column Integer Индекс столбца диапазона; индексация столбца начинается с 1.
numRows Integer Количество возвращаемых строк.

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

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

Авторизация

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

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

getRange(row, column, numRows, numColumns)

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

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(1, 1, 3, 3);
var values = range.getValues();

// Print values from a 3x3 box.
for (var row in values) {
  for (var col in values[row]) {
    Logger.log(values[row][col]);
  }
}

Параметры

Имя Тип Описание
row Integer Начальный индекс строки диапазона; индексация строк начинается с 1.
column Integer Индекс начального столбца диапазона; индексация столбца начинается с 1.
numRows Integer Количество возвращаемых строк.
numColumns Integer Количество возвращаемых столбцов.

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

Range — диапазон, соответствующий указанной области.

Авторизация

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

  • 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

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

getRowGroup(rowIndex, groupDepth)

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

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

// Returns the group whose control index is at row 2 and has a depth of 1, or
// null if the group doesn’t exist.
var rowGroup = sheet.getRowGroup(2, 1);

Параметры

Имя Тип Описание
rowIndex Integer Индекс строки переключателя управления группой или индекс внутри группы.
groupDepth Integer Глубина группы.

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

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

Авторизация

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

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

getRowGroupControlPosition()

Возвращает GroupControlTogglePosition для всех групп строк на листе.

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

// GroupControlTogglePosition.AFTER if the row grouping control toggle is shown after the
// group.
var rowGroupControlPosition = sheet.getRowGroupControlPosition();

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

GroupControlTogglePositiontrue , если переключатель управления группировкой строк отображается после группы на этом листе, и false в противном случае.

Авторизация

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

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

getRowGroupDepth(rowIndex)

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

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

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

// 1 if there is a group over rows 1 through 3
var groupDepth = sheet.getRowGroupDepth(1);

Параметры

Имя Тип Описание
rowIndex Integer Индекс строки.

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

Integer — Глубина группы строки по данному индексу.

Авторизация

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

  • 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

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

getSlicers()

Возвращает массив слайсеров на листе.

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

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

// Gets all slicers in the spreadsheet.
const slicers = sheet.getSlicers();

// Logs the slicer titles to the console.
for (const slicer of slicers) {
  console.log(slicer.getTitle());
}

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

Slicer[] — Список слайсеров на этом листе.

Авторизация

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

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

getTabColorObject()

Получает цвет вкладки листа или null , если вкладка листа не имеет цвета.

// This example assumes there is a sheet named "Sheet1"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("Sheet1");
var color = first.getTabColorObject();

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

Color — The sheet tab color, or null if the sheet tab has no color.

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

getType()

Returns the type of the sheet.

The default type of sheet is SheetType.GRID . A sheet that contains a single embedded object such as an EmbeddedChart is an SheetType.OBJECT sheet.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
Logger.log(sheet.getType());

Return

SheetType — The type of the 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

hasHiddenGridlines()

Returns true if the sheet's gridlines are hidden; otherwise returns false . Gridlines are visible by default.

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

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

// Checks if the spreadsheet has hidden gridelines and logs the result to the console.
console.log(sheet.hasHiddenGridlines());

Return

Booleantrue if gridlines are 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

hideColumn(column)

Hides the column or columns in the given range.

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

Parameters

Name Type Description
column Range The column 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

hideColumns(columnIndex)

Hides a single column at the given index. Use 1-index for this method.

To hide more than one column using an index, use hideColumns(columnIndex, numColumns) .

To hide more than one column using a range, use hideColumn() .

let ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheets()[0];
// Hides the first column
sheet.hideColumns(1);

Parameters

Name Type Description
columnIndex Integer The index of the column 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

hideColumns(columnIndex, numColumns)

Hides one or more consecutive columns starting at the given index. Use 1-index for this method.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Hides the first three columns
sheet.hideColumns(1, 3);

Parameters

Name Type Description
columnIndex Integer The starting index of the columns to hide.
numColumns Integer The number of columns 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

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

hideRows(rowIndex)

Hides the row at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Hides the first row
sheet.hideRows(1);

Parameters

Name Type Description
rowIndex Integer The index of the row 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

hideRows(rowIndex, numRows)

Hides one or more consecutive rows starting at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Hides the first three rows
sheet.hideRows(1, 3);

Parameters

Name Type Description
rowIndex Integer The starting index of the rows to hide.
numRows Integer The number of rows 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

hideSheet()

Hides this sheet. Has no effect if the sheet is already hidden. If this method is called on the only visible sheet, it throws an exception.

var sheet = SpreadsheetApp.getActiveSheet();
sheet.hideSheet();

Return

Sheet — The current 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

insertChart(chart)

Adds a new chart to this sheet.

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

// This creates a simple bar chart from the first three rows
// of the first two columns of the spreadsheet
var chart = sheet.newChart()
    .setChartType(Charts.ChartType.BAR)
    .addRange(sheet.getRange("A1:B4"))
    .setPosition(5, 5, 0, 0)
    .setOption("title", "Dynamic Chart")
    .build();
sheet.insertChart(chart);

Parameters

Name Type Description
chart EmbeddedChart The chart to insert.

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

insertColumns(columnIndex)

Inserts a blank column in a sheet at the specified location.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Shifts all columns by one
sheet.insertColumns(1);

Parameters

Name Type Description
columnIndex Integer The index indicating where to insert a column.

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

insertColumns(columnIndex, numColumns)

Inserts one or more consecutive blank columns in a sheet starting at the specified location.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Shifts all columns by three
sheet.insertColumns(1, 3);

Parameters

Name Type Description
columnIndex Integer The index indicating where to insert a column.
numColumns Integer The number of columns to insert.

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

insertImage(blobSource, column, row)

Inserts a BlobSource 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 BlobSource 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

insertRows(rowIndex)

Inserts a blank row in a sheet at the specified location.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Shifts all rows down by one
sheet.insertRows(1);

Parameters

Name Type Description
rowIndex Integer The index indicating where to insert a row.

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

insertRows(rowIndex, numRows)

Inserts one or more consecutive blank rows in a sheet starting at the specified location.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Shifts all rows down by three
sheet.insertRows(1, 3);

Parameters

Name Type Description
rowIndex Integer The index indicating where to insert a row.
numRows Integer The number of rows to insert.

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

insertSlicer(range, anchorRowPos, anchorColPos)

Adds a new slicer to this sheet.

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

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

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

// Inserts the slicer with a random range into the sheet.
const insertSlicers = sheet.insertSlicer(range.randomize(), 1, 10);

// Logs the insert slicer result to the console.
console.log(insertSlicers);

Parameters

Name Type Description
range Range The range over which slicer slicer is created.
anchorRowPos Integer The slicer's top side is anchored in this row.
anchorColPos Integer The slicer's top side is anchored in this col.

Return

Slicer — The newly inserted slicer.

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

insertSlicer(range, anchorRowPos, anchorColPos, offsetX, offsetY)

Adds a new slicer to this sheet.

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

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

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

// Inserts a slicer using the random range function.
const insertSlicers = sheet.insertSlicer(range.randomize(), 1, 10, 0, 0);

// Logs the insert slicer result to the console.
console.log(insertSlicers);

Parameters

Name Type Description
range Range The range over which slicer slicer is created.
anchorRowPos Integer The slicer's top side is anchored in this row.
anchorColPos Integer The slicer's top side is anchored in this col.
offsetX Integer The horizontal offset from cell corner in pixels.
offsetY Integer The vertical offset from cell corner in pixels.

Return

Slicer — The newly inserted slicer.

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

Booleantrue 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

isRightToLeft()

Returns true if this sheet layout is right-to-left. Returns false if the sheet uses the default left-to-right layout.

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

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

// Checks if a spreadsheet is ordered from right to left and logs the result to the console.
console.log(sheet.isRightToLeft());

Return

Booleantrue if right-to-left; 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

Booleantrue 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

Booleantrue 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

isSheetHidden()

Returns true if the sheet is currently hidden.

var sheet = SpreadsheetApp.getActiveSheet();
if (sheet.isSheetHidden()) {
  // do something...
}

Return

Booleantrue if the sheet 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

moveColumns(columnSpec, destinationIndex)

Moves the columns selected by the given range to the position indicated by the destinationIndex . The columnSpec itself does not have to exactly represent an entire column or group of columns to move—it selects all columns that the range spans.

// The code below moves rows A-B to destination index 5.
// This results in those columns becoming columns C-D.
var sheet = SpreadsheetApp.getActiveSheet();
// Selects column A and column B to be moved.
var columnSpec = sheet.getRange("A1:B1");
sheet.moveColumns(columnSpec, 5);

Parameters

Name Type Description
columnSpec Range A range spanning the columns that should be moved.
destinationIndex Integer The index that the columns should be moved to. Note that this index is based on the coordinates before the columns are moved. Existing data is shifted right to make room for the moved columns while the source columns are removed from the grid. Therefore, the data may end up at a different index than originally specified.

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

moveRows(rowSpec, destinationIndex)

Moves the rows selected by the given range to the position indicated by the destinationIndex . The rowSpec itself does not have to exactly represent an entire row or group of rows to move—it selects all rows that the range spans.

// The code below moves rows 1-2 to destination index 5.
// This results in those rows becoming rows 3-4.
var sheet = SpreadsheetApp.getActiveSheet();
// Selects row 1 and row 2 to be moved.
var rowSpec = sheet.getRange("A1:A2");
sheet.moveRows(rowSpec, 5);

Parameters

Name Type Description
rowSpec Range A range spanning the rows that should be moved.
destinationIndex Integer The index that the rows should be moved to. Note that this index is based on the coordinates before the rows are moved. Existing data is shifted down to make room for the moved rows while the source rows are removed from the grid. Therefore, the data may end up at a different index than originally specified.

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

newChart()

Returns a builder to create a new chart for this sheet.

This example shows how to create a new chart:

var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:B8");
var chartBuilder = sheet.newChart();
chartBuilder.addRange(range)
    .setChartType(Charts.ChartType.LINE)
    .setPosition(2, 2, 0, 0)
    .setOption('title', 'My Line Chart!');
sheet.insertChart(chartBuilder.build());

Return

EmbeddedChartBuilder — A builder to create a new chart.


protect()

Creates an object that can protect the sheet from being edited except by users who have permission. Until the script actually changes the list of editors for the sheet (by calling Protection.removeEditor(emailAddress) , Protection.removeEditor(user) , Protection.removeEditors(emailAddresses) , Protection.addEditor(emailAddress) , Protection.addEditor(user) , Protection.addEditors(emailAddresses) , or setting a new value for Protection.setDomainEdit(editable) ), the permissions mirror those of the spreadsheet itself, which effectively means that the sheet remains unprotected. If the sheet is already protected, this method returns an object representing its existing protection settings. A protected sheet may include unprotected regions.

// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Return

Protection — An object representing the protection settings.

Authorization

Scripts that use this method require authorization with one or more of the following scopes :

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

removeChart(chart)

Removes a chart from the parent sheet.

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

// This removes all the embedded charts from the spreadsheet
var charts = sheet.getCharts();
for (var i in charts) {
  sheet.removeChart(charts[i]);
}

Parameters

Name Type Description
chart EmbeddedChart The chart 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

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

setColumnGroupControlPosition(position)

Sets the position of the column group control toggle on the sheet.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.setColumnGroupControlPosition(SpreadsheetApp.GroupControlTogglePosition.AFTER);

Parameters

Name Type Description
position GroupControlTogglePosition The position of the column group control toggle.

Return

Sheet — This sheet, 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

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

setColumnWidths(startColumn, numColumns, width)

Sets the width of the given columns in pixels.

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

// Sets the first three columns to a width of 200 pixels
sheet.setColumnWidths(1, 3, 200);

Parameters

Name Type Description
startColumn Integer The starting column position to change.
numColumns Integer The number of columns to change.
width Integer The width in pixels to set it to.

Return

Sheet — This sheet, 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

setConditionalFormatRules(rules)

Replaces all currently existing conditional format rules in the sheet with the input rules. Rules are evaluated in their input order.

// Remove one of the existing conditional format rules.
var sheet = SpreadsheetApp.getActiveSheet();
var rules = sheet.getConditionalFormatRules();
rules.splice(1, 1); // Deletes the 2nd format rule.
sheet.setConditionalFormatRules(rules);

Parameters

Name Type Description
rules ConditionalFormatRule[] The new conditional format rules.

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

setHiddenGridlines(hideGridlines)

Hides or reveals the sheet gridlines.

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

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

// Hides the gridlines in the sheet.
sheet.setHiddenGridlines(true);

Parameters

Name Type Description
hideGridlines Boolean If true , hide gridlines in this sheet; otherwise show the gridlines.

Return

Sheet — This sheet, 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

setName(name)

Sets the sheet name.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setName("not first anymore");

Parameters

Name Type Description
name String The new name for the sheet.

Return

Sheet — This sheet, 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

setRightToLeft(rightToLeft)

Sets or unsets the sheet layout to right-to-left.

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

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

// Sets the sheet layout, so that the sheet is ordered from right to left.
sheet.setRightToLeft(true);

Parameters

Name Type Description
rightToLeft Boolean If true , the sheet layout is set to right-to-left, with cell A1 at the top right corner. If false , the sheet layout is set to the default left-to-right, with cell A1 at the top left.

Return

Sheet — This sheet, 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

setRowGroupControlPosition(position)

Sets the position of the row group control toggle on the sheet.

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.setRowGroupControlPosition(SpreadsheetApp.GroupControlTogglePosition.AFTER);

Parameters

Name Type Description
position GroupControlTogglePosition The position of the row group control toggle.

Return

Sheet — This sheet, 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 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

setRowHeights(startRow, numRows, height)

Sets the height of the given rows in pixels. By default, rows grow to fit cell contents. If you want to force rows to a specified height, use setRowHeightsForced(startRow, numRows, height) .

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

// Sets the first three rows to a height of 20 pixels
sheet.setRowHeights(1, 3, 20);

Parameters

Name Type Description
startRow Integer The starting row position to change.
numRows Integer The number of rows to change.
height Integer The height in pixels to set it to.

Return

Sheet — This sheet, 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

setRowHeightsForced(startRow, numRows, height)

Sets the height of the given rows in pixels. By default, rows grow to fit cell contents. When you use setRowHeightsForced , rows are forced to the specified height even if the cell contents are taller than the row height.

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

// Sets the first three rows to a height of 5 pixels.
sheet.setRowHeightsForced(1, 3, 5);

Parameters

Name Type Description
startRow Integer The starting row position to change.
numRows Integer The number of rows to change.
height Integer The height in pixels to set it to.

Return

Sheet — This sheet, 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

setTabColor(color)

Sets the sheet tab color.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setTabColor("ff0000"); // Set the color to red.
first.setTabColor(null); // Unset the color.

Parameters

Name Type Description
color String A color code in CSS notation (like '#ffffff' or 'white' ), or null to reset the tab color.

Return

Sheet — This sheet, 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

setTabColorObject(color)

Sets the sheet tab color.

// This example assumes there is a sheet named "Sheet1"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("Sheet1");
var color = SpreadsheetApp.newColor()
    .setThemeColor(SpreadsheetApp.ThemeColorType.ACCENT1)
    .build();
first.setTabColorObject(color); // Set the color to theme accent 1.
first.setTabColorObject(null); // Unset the color.

Parameters

Name Type Description
color Color The sheet tab color to set.

Return

Sheet — This sheet, 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

showColumns(columnIndex)

Unhides the column at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Unhides the first column
sheet.showColumns(1);

Parameters

Name Type Description
columnIndex Integer The index of the column to unhide.

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

showColumns(columnIndex, numColumns)

Unhides one or more consecutive columns starting at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Unhides the first three columns
sheet.showColumns(1, 3);

Parameters

Name Type Description
columnIndex Integer The starting index of the columns to unhide.
numColumns Integer The number of columns to unhide.

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

showRows(rowIndex)

Unhides the row at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Unhides the first row
sheet.showRows(1);

Parameters

Name Type Description
rowIndex Integer The index of the row to unhide.

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

showRows(rowIndex, numRows)

Unhides one or more consecutive rows starting at the given index.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Unhides the first three rows
sheet.showRows(1, 3);

Parameters

Name Type Description
rowIndex Integer The starting index of the rows to unhide.
numRows Integer The number of rows to unhide.

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

showSheet()

Makes the sheet visible. Has no effect if the sheet is already visible.

var sheet = SpreadsheetApp.getActiveSheet();
sheet.showSheet();

Return

Sheet — The current 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

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

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

updateChart(chart)

Updates the chart on this sheet.

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

// This code is going to loop through all the charts and change them to
// column charts
var charts = sheet.getCharts();
for (var i in charts) {
  var chart = charts[i];
  var newChart = chart
      .modify()
      .setChartType(Charts.ChartType.COLUMN)
      .build();
  sheet.updateChart(newChart);
}

Parameters

Name Type Description
chart EmbeddedChart The chart to update.

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

Deprecated methods