Скрипти Google Apps Script у таблицях Sheets

//

Расширение Google Таблиц, Расширение Google Таблиц //developers.google.com/apps-script/guides/sheets
Обзор API Google Таблиц //developers.google.com/sheets/api/guides/concepts

to be //

Обзор API Google Таблиц

//developers.google.com/sheets/api/guides/concepts

  • SpreadsheetApp
    • Spreadsheet электронная таблица
      Основной объект в Google Таблицах, который может содержать несколько листов, каждый из которых содержит структурированную информацию, содержащуюся в ячейках. Ресурс Spreadsheet представляет каждую электронную таблицу и имеет уникальное значение spreadsheetId , содержащее буквы, цифры, дефисы или символы подчеркивания. Идентификатор таблицы можно найти в URL-адресе Google Таблиц

      • Sheet Страница или вкладка в электронной таблице. Ресурс Sheet представляет каждый лист и имеет уникальный заголовок и числовое значение sheetId . Вы можете найти идентификатор листа в URL-адресе Google Таблиц:
        • Range диапазон
          • Клетка Отдельное поле текста или данных на листе. Ячейки расположены в строках и столбцах и могут быть сгруппированы как диапазон ячеек. Ресурс CellData представляет каждую ячейку, но не имеет уникального значения идентификатора. Вместо этого координаты строки и столбца идентифицируют ячейки.

Объекты, свойства и методы в таблицах Sheets

//

Класс приложения электронных таблиц SpreadsheetApp

//developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app
Главный родительский класс/объект электронных таблиц Google Sheets позволяет создавать и открывать табличные документы

  • create(name): Spreadsheet
    create(name, rows, columns): Spreadsheet Creates a new spreadsheet with the given name and the specified number of rows and columns

    • name: String The name for the spreadsheet.
    • rows: Integer The number of rows for the spreadsheet.
    • columns: Integer The number of columns for the spreadsheet.
  • openById(id: string): SpreadsheetApp.Spreadsheet //
  • getUi(): Ui Returns an instance of the spreadsheet's user-interface environment that allows the script to add features like menus, dialogs, and sidebars. A script can only interact with the UI for the current instance of an open spreadsheet, and only if the script is bound to the spreadsheet. For more information, see the guides to menus and dialogs and sidebars.
  • getActive(): SpreadsheetApp.Spreadsheet
    Returns the currently active spreadsheet, or null if there is none.
    Functions that are run in the context of a spreadsheet can get a reference to the corresponding Spreadsheet object by calling this function.
  • getActiveSpreadsheet(): SpreadsheetApp.Spreadsheet
    Returns the currently active spreadsheet, or null if there is none
  • getActiveSheet(): SpreadsheetApp.Sheet
    Gets the active sheet in a spreadsheet.
    The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.
  • getActiveRangeList(): SpreadsheetApp.RangeList
    Returns the list of active ranges in the active sheet or null if there are no ranges selected. The active range containing the current highlighted cell is placed last in the list. If there is a single range selected, this behaves as a getActiveRange() call.
  • getActiveRange(): SpreadsheetApp.Range
    Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
    This generally means the range that a user has selected in the active sheet, but in a custom function it refers to the cell being actively recalculated.
  • getCurrentCell(): SpreadsheetApp.Range
    Returns the current (highlighted) cell that is selected in one of the active ranges in the active sheet or null if there is no current cell.

Spreadsheet

//developers.google.com/apps-script/reference/spreadsheet/spreadsheet
Класс доступа к содержанию файла Google Sheets. Распространенными операциями являются добавление новых листов и добавление соавторов.

  • getName(): String Gets the name of the document
  • getSheetId(): Integer Returns the ID of the sheet represented by this object
    This is an ID for the sheet that is unique to the spreadsheet. The ID is a monotonically increasing integer assigned at sheet creation time that is independent of sheet position. This is useful in conjunction with methods such as Range.copyFormatToRange(gridId, column, columnEnd, row, rowEnd) that take a gridId parameter rather than a Sheet instance.
  • deleteSheet(sheet: Sheet): void Deletes the specified sheet
  • addEditor(user: User): Spreadsheet Adds the given user to the list of editors for the Spreadsheet. If the user was already on the list of viewers, this method promotes the user out of the list of viewers.
  • getSheetValues(startRow, startColumn, numRows, numColumns): Object[][] извлекает двумерный массив значений
    Returns the rectangular grid of values for this range starting at the given coordinates. A -1 value given as the row or column position is equivalent to getting the very last row or column that has data in the sheet.

    • startRow Integer The position of the starting row от 1
    • startColumn Integer The position of the starting column от 1
    • numRows Integer The number of rows to return values for.
    • numColumns Integer The number of columns to return values for.

Sheet

Доступ и изменение таблицы //developers.google.com/apps-script/reference/spreadsheet/sheet

  • getParent(): Spreadsheet Returns the Spreadsheet that contains this sheet
  • getName(): String Returns the name of the sheet
  • getDataRange(): Range Возвращает диапазон, в котором присутствуют все данные листа
  • getLastRow(): Integer
    getLastColumn(): Integer Returns the position of the last row/column that has sheet content
  • getRange(row, column): Range
    getRange(row, column, numRows): Range
    getRange(row, column, numRows, numColumns): Range
    getRange(a1Notation): Range методы предоставляют различные способы получить диапазон таблицы в т.ч. в нотации A1 или R1C1

    • row: Integer The starting row index of the range; row indexing starts with 1
    • column: Integer The starting column index of the range; column indexing starts with 1
    • numRows: Integer The number of rows to return
    • numColumns: Integer The number of columns to return
    • a1Notation: String The range to return, as specified in A1 notation or R1C1 notation
  • showSheet(): Sheet Makes the sheet visible. Has no effect if the sheet is already visible. Return The current sheet
  • getRangeList(a1Notations): RangeList формирует коллекцию RangeList из диапазонов на одном листе
    • a1Notations String[] массив списка диапазонов для включение в нотации A1 или R1C1

//

Класс диапазона ячеек Range

//developers.google.com/apps-script/reference/spreadsheet/range
Лист таблицы состоит из отдельных ячеек, однако класс соответствующий отдельной ячейке в App Script не предусмотрен. Доступ и изменение в отдельной ячейке или в прямоугольной группе смежных ячеек на листе Sheet реализуется классом диапазона ячеек Range.

Навигация

  • getSheet(): Sheet возвращает лист, в котором находится диапазон
  • getCell(row, column): Range возвращает поддиапазон исходного диапазона содержащий  единственную ячейку
    • row: Integer относительный номер строки в исходном диапазоне (нумерация от 1)
    • column: Integer относительный номер колонки в исходном диапазоне (нумерация от 1)
  • getRow(): Integer / getColumn(): Integer возвращает номер строки/колонки начальной позиции диапазона на листе
  • getNumRows() Integer Возвращает количество строк в этом диапазоне
  • getNumColumns() Integer Возвращает количество столбцов в этом диапазоне
  • getLastRow() Integer Возвращает позицию конца строки
  • getLastColumn() Integer Возвращает позицию конца столбца
  • getGridId() Integer Возвращает идентификатор сетки родительского листа диапазона.
  • getWidth(): Integer Returns the width of the range in columns (The number of columns in the range)
  • getHeight() Integer Возвращает высоту диапазона.
  • isPartOfMerge(): Boolean Returns true if the cells in the current range overlap any merged cells

Обработка значений

  • isBlank(): Boolean Returns true if the range is totally blank (true if the range is blank; false otherwise)
  • isChecked(): Boolean Returns whether all cells in the range have their checkbox state as 'checked'. Returns null if some cells are checked and the rest unchecked, or if some cells do not have checkbox data validation.
  • getValue() Object Возвращает значение верхней левой ячейки диапазона.
  • getValues() Object[][] Возвращает прямоугольную сетку значений для этого диапазона.
  • getDisplayValue(): String возвращает отображаемое значение верхней левой ячейки диапазона, которое учитывает форматирование даты, времени и валюты, включая форматы, автоматически применяемые в настройках локали электронной таблицы; пустые ячейки возвращают пустую строку
  • getDisplayValues(): String[][] возвращает двумерный массив отображаемых значений, проиндексированных по строкам, а затем по столбцам. Remember that while a range index starts at 1, 1 , the JavaScript array is indexed from [0][0] .
  • setValue(value): Range
  • setValues(values): Range
  • getRichTextValue() RichTextValue Возвращает значение Rich Text для верхней левой ячейки диапазона или null , если значение ячейки не является текстом.
    getRichTextValues() RichTextValue[][] Возвращает значения форматированного текста для ячеек в диапазоне.

Формула

  • getFormula(): String Возвращает формулу (нотация A1) для верхней левой ячейки диапазона или пустую строку, если ячейка пуста или не содержит формулы
  • getFormulaR1C1(): String Возвращает формулу (обозначение R1C1) для заданной ячейки или null , если нет.
  • getFormulas(): String[][] Возвращает формулы (нотация A1) для ячеек в диапазоне.
  • getFormulasR1C1(): String[][] Возвращает формулы (нотация R1C1) для ячеек в диапазоне.
  • getNote() String Возвращает заметку, связанную с заданным диапазоном.
  • getNotes() String[][] Возвращает примечания, связанные с ячейками в диапазоне.
  • getNumberFormat(): String Get the number or date formatting of the top-left cell of the given range
  • setNumberFormat(numberFormat): Range Sets the number or date format to the given formatting string. The accepted format patterns are described in the Sheets API documentation
    • numberFormat: String A number format string //developers.google.com
      • "@" формат Обычный текст отменяет приведение строкового значения к другим типам

Модификация

  • sort(sortSpecObj)
    range.sort([{column: 2, ascending: false}, {column: 1, ascending: true}]);
  • removeDuplicates(): Range
    removeDuplicates(columnsToCompare): Range Removes rows within this range that contain values that are duplicates of values in any previous row. Rows with identical values but different letter cases, formatting, or formulas are considered to be duplicates. This method also removes duplicates rows hidden from view (for example, due to a filter). Content outside of this range isn't removed

    • columnsToCompare: Integer[] The columns to analyze for duplicate values. If no columns are provided then all columns are analyzed for duplicates.
  • merge(): Range Merges the cells in the range together into a single block.
  • randomize(): Range Randomizes the order of the rows in the given range

Класс списка диапазонов RangeList

//developers.google.com/apps-script/reference/spreadsheet/range-list
Класс реализует коллекцию из одного или нескольких экземпляров Range на одном листе для одновременной обработки всех диапазонов, поэтому содержит сходный набор методов.

Ui

Экземпляр среды интерфейса пользователя приложения Google позволяет скрипту добавлять меню, диалоговые окна и боковые панели. Сценарий может взаимодействовать с пользовательским интерфейсом только для текущего экземпляра открытого редактора и только в том случае, если сценарий привязан к контейнеру редактора.
//developers.google.com/apps-script/reference/base/ui.html

  • alert(prompt: string): Button
    alert(prompt: string, buttons: ButtonSet): Button The message to display in the dialog box

    • buttons: ButtonSet The button set to display in the dialog box
      • OK Enum A single "OK" button, indicating an informational message that can only be dismissed
      • OK_CANCEL Enum An "OK" button and a "Cancel" button, allowing the user to either proceed with or halt an operation
      • YES_NO Enum A "Yes" button and a "No" button, allowing the user to answer a yes/no question
      • YES_NO_CANCEL Enum A "Yes" button, a "No" button, and a "Cancel" button, allowing the user to either answer a yes/no question or halt an operation
  • prompt(prompt: string): PromptResponse The message to display in the dialog box.
    Opens an input dialog box in the user's editor with the given message and an "OK" button. This method suspends the server-side script while the dialog is open. The script resumes after the user dismisses the dialog, but Jdbc connections and LockService locks don't persist across the suspension. For more information, see the guide to dialogs and sidebars.
  • showModalDialog(userInterface: Object, title: string): void An HtmlOutput representing the interface to display.
  • showModelessDialog(userInterface: Object, title: string): void An HtmlOutput representing the interface to display.
    Opens a modeless dialog box in the user's editor with custom client-side content. This method does not suspend the server-side script while the dialog is open. To communicate with the server-side script, the client-side component must make asynchronous callbacks using the google.script API for HtmlService. To close the dialog programmatically, call google.script.host.close() on the client side of an HtmlService web app. For more information, see the guide to dialogs and sidebars.
  • showSidebar(userInterface: Object): void An HtmlOutput representing the interface to display.
    Opens a sidebar in the user's editor with custom client-side content. This method does not suspend the server-side script while the sidebar is open. To communicate with the server-side script, the client-side component must make asynchronous callbacks using the google.script API for HtmlService. To close the sidebar programmatically, call google.script.host.close() on the client side of an HtmlService web app. For more information, see the guide to dialogs and sidebars.
  • createMenu(caption: string): Menu The label for the menu, with all major words capitalized for a top-level menu, or only the first word capitalized for a sub-menu.

PromptResponse

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

  • getResponseText(): String Gets the text that the user entered in the dialog's input field. The text is available even if the user closed the dialog by clicking a button with a negative connotation, like "Cancel" or the close button in the dialog's title bar. getSelectedButton() can help to determine whether the user intended the response text to be valid
  • getSelectedButton(): Button Gets the button that the user clicked to dismiss the dialog. If the user clicked the close button that is included in every dialog's title bar, this method returns Button.CLOSE.
    • return Button The button that the user clicked
      • CLOSE Enum The standard close button displayed in every dialog's title bar. This button is not explicitly added to a dialog, and it cannot be removed
      • OK Enum An "OK" button, indicating that an operation should proceed
      • CANCEL Enum A "Cancel" button, indicating that an operation should not proceed
      • YES Enum A "Yes" button, indicating a positive response to a question
      • NO Enum A "No" button, indicating a negative response to a question

Menu

  • addItem(caption: string, functionName: string): Menu
    The label for the menu item, with only the first word capitalized
  • addSeparator(): Menu
    Adds a visual separator to the menu
  • addSubMenu(menu: Menu): Menu
    The sub-menu, constructed like a top-level menu
  • addToUi(): void
    Inserts the menu into the instance of the editor's user interface.

Leave a Reply