### Example Usage Source: https://developers.google.com/apps-script/reference/slides/speaker-spotlight Demonstrates how to get a SpeakerSpotlight object and log its page element type. ```APIDOC ```javascript const slide = SlidesApp.getActivePresentation().getSlides()[0]; const speakerSpotlight = slide.getPageElements()[0]; console.log( `Page element is of type: ${ speakerSpotlight.getPageElementType().toString()}`, ); ``` ``` -------------------------------- ### Main Setup Function Source: https://developers.google.com/apps-script/samples/automations/import-csv-sheets Sets up the primary destination spreadsheet and processes CSV files, creating them in the source folder if they don't exist. It also installs a project trigger. ```javascript // Sets up primary destination spreadsheet const sheet = setupPrimarySpreadsheet_(folderAppPrimary); // Gets the CSV files data - refer to the SampleData.gs file to view. const csvFiles = getCSVFilesData(); // Processes each CSV file. for (const file of csvFiles) { // Creates CSV file in source folder if it doesn't exist. if (!fileExists_(file.name, folderSource)) { const csvFileId = DriveApp.createFile( file.name, file.csv, MimeType.CSV, ); console.log(`Created Sample CSV: ${file.name}`); csvFileId.moveTo(folderSource); } } } // Installs (or recreates) project trigger installTrigger(); console.log(`Setup completed for: ${APP_TITLE}`); } ``` -------------------------------- ### Main Setup Function Source: https://developers.google.com/apps-script/samples/automations/import-csv-sheets?hl=tr Sets up the primary destination spreadsheet and processes CSV files. It ensures CSV files exist in the source folder and installs a project trigger. ```javascript /** * Sets up primary destination spreadsheet and processes CSV files. */ function setup() { // Sets up primary destination spreadsheet const sheet = setupPrimarySpreadsheet_(folderAppPrimary); // Gets the CSV files data - refer to the SampleData.gs file to view. const csvFiles = getCSVFilesData(); // Processes each CSV file. for (const file of csvFiles) { // Creates CSV file in source folder if it doesn't exist. if (!fileExists_(file.name, folderSource)) { const csvFileId = DriveApp.createFile( file.name, file.csv, MimeType.CSV, ); console.log(`Created Sample CSV: ${file.name}`); csvFileId.moveTo(folderSource); } } } // Installs (or recreates) project trigger installTrigger(); console.log(`Setup completed for: ${APP_TITLE}`); } ``` -------------------------------- ### Go Quickstart Application Source: https://developers.google.com/apps-script/api/quickstart/go This Go program demonstrates how to authenticate with Google OAuth 2.0, create a new Google Apps Script project, and update its content. Ensure you have a 'credentials.json' file in your working directory. ```go package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/option" "google.golang.org/api/script/v1" ) // Retrieve a token, saves the token, then returns the generated client. func getClient(config *oauth2.Config) *http.Client { // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. tokFile := "token.json" tok, err := tokenFromFile(tokFile) if err != nil { tok = getTokenFromWeb(config) saveToken(tokFile, tok) } return config.Client(context.Background(), tok) } // Request a token from the web, then returns the retrieved token. func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) fmt.Printf("Go to the following link in your browser then type the " + "authorization code: \n%v\n", authURL) var authCode string if _, err := fmt.Scan(&authCode); err != nil { log.Fatalf("Unable to read authorization code: %v", err) } tok, err := config.Exchange(context.TODO(), authCode) if err != nil { log.Fatalf("Unable to retrieve token from web: %v", err) } return tok } // Retrieves a token from a local file. func tokenFromFile(file string) (*oauth2.Token, error) { f, err := os.Open(file) if err != nil { return nil, err } defer f.Close() tok := &oauth2.Token{} err = json.NewDecoder(f).Decode(tok) return tok, err } // Saves a token to a file path. func saveToken(path string, token *oauth2.Token) { fmt.Printf("Saving credential file to: %s\n", path) f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatalf("Unable to cache oauth token: %v", err) } defer f.Close() json.NewEncoder(f).Encode(token) } func main() { ctx := context.Background() b, err := os.ReadFile("credentials.json") if err != nil { log.Fatalf("Unable to read client secret file: %v", err) } // If modifying these scopes, delete your previously saved token.json. config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/script.projects") if err != nil { log.Fatalf("Unable to parse client secret file to config: %v", err) } client := getClient(config) srv, err := script.NewService(ctx, option.WithHTTPClient(client)) if err != nil { log.Fatalf("Unable to retrieve Script client: %v", err) } req := script.CreateProjectRequest{Title: "My Script"} createRes, err := srv.Projects.Create(&req).Do() if err != nil { // The API encountered a problem. log.Fatalf("The API returned an error: %v", err) } content := &script.Content{ ScriptId: createRes.ScriptId, Files: []*script.File{{ Name: "hello", Type: "SERVER_JS", Source: "function helloWorld() {\n console.log('Hello, world!');}", }, { Name: "appsscript", Type: "JSON", Source: "{\"timeZone\":\"America/New_York\",\"exceptionLogging\":" + "\"CLOUD\"}", }}, } updateContentRes, err := srv.Projects.UpdateContent(createRes.ScriptId, content).Do() if err != nil { // The API encountered a problem. log.Fatalf("The API returned an error: %v", err) } log.Printf("https://script.google.com/d/%v/edit", updateContentRes.ScriptId) } ``` -------------------------------- ### Get Calendar Event Start Time Source: https://developers.google.com/apps-script/class_calendarevent Retrieves and logs the start time of a specific calendar event. This example demonstrates how to open a calendar, find an event within a given time range, and then get its start time. ```javascript const calendar = CalendarApp.getCalendarById( 'abc123456@group.calendar.google.com', ); const event = calendar.getEvents( new Date('Feb 01, 2023 16:10:00'), new Date('Feb 01, 2023 16:25:00'), )[0]; const startTime = event.getStartTime(); console.log(startTime); ``` -------------------------------- ### Setup Sample Data Files Source: https://developers.google.com/apps-script/samples/automations/import-csv-sheets Initializes the application by creating necessary folders and sample CSV files. This function is part of the setup process for the application. ```javascript /** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This file contains functions that set up the folders and sample files used to demo the application. * * Sample data for the application is stored in the SampleData.gs file. */ // Global variables for sample setup. const INCLUDE_SAMPLE_DATA_FILES = true; // Set to true to create sample data files, false to skip. /** * Runs the setup for the sample. * 1) Creates the application folder and subfolders for unprocessed/processed CSV files. * from global variables APP_FOLDER | SOURCE_FOLDER | PROCESSED_FOLDER * 2) Creates the sample Sheets spreadsheet in the application folder. * from global variable SHEET_REPORT_NAME * 3) Creates CSV files from sample data in the unprocessed files folder. * from variable SAMPLE_DATA in SampleData.gs. * 4) Creates an installable trigger to run process automatically at a specified time interval. */ function setupSample() { console.log(`Application setup for: ${APP_TITLE}`); // Creates application folder. const folderAppPrimary = getApplicationFolder_(APP_FOLDER); // Creates supporting folders. const folderSource = getFolder_(SOURCE_FOLDER); const folderProcessed = getFolder_(PROCESSED_FOLDER); console.log( `Application folders: ${folderAppPrimary.getName()}, ${folderSource.getName()}, ${folderProcessed.getName()}`, ); if (INCLUDE_SAMPLE_DATA_FILES) { ``` -------------------------------- ### Get Start Connection Source: https://developers.google.com/apps-script/reference/slides/line Retrieves the connection site at the start of the line. ```APIDOC ## getStartConnection() ### Description Returns the connection at the beginning of the line, or `null` if there is no connection. ### Method `getStartConnection()` ### Return Type `ConnectionSite|null` ``` -------------------------------- ### Get Installation Source Source: https://developers.google.com/apps-script/reference/script/script-app Returns an enum indicating how the script was installed as an add-on. ```javascript ScriptApp.getInstallationSource(); ``` -------------------------------- ### Setup Application with Sample Data Source: https://developers.google.com/apps-script/samples/automations/aggregate-document-content Initiates the application setup process by calling the `setupConfig` function with a boolean argument to enable sample data configuration. ```Google Apps Script function setupWithSamples() { setupConfig(true); } ``` -------------------------------- ### Run Go Sample Application Source: https://developers.google.com/apps-script/api/quickstart/go Build and run the Go sample application from your working directory. The first time you run this, it will prompt for authorization. ```bash go run quickstart.go ``` -------------------------------- ### Get Start Arrow Style Source: https://developers.google.com/apps-script/reference/slides/line Retrieves the arrow style at the start of the line. ```APIDOC ## getStartArrow() ### Description Gets the `ArrowStyle` of the arrow at the beginning of the line. ### Method `getStartArrow()` ### Return Type `ArrowStyle` ``` -------------------------------- ### SelectSingle Configuration Example Source: https://developers.google.com/apps-script/reference/data-studio/select-single Demonstrates how to create a SelectSingle configuration object, add options to it, and set various properties like ID, name, help text, and allow override. ```APIDOC ## SelectSingle Contains select single information for the config. Its properties determine how the select single is displayed in Data Studio. ```javascript const cc = DataStudioApp.createCommunityConnector(); const config = cc.getConfig(); const option1 = config.newOptionBuilder().setLabel('option label').setValue('option_value'); const option2 = config.newOptionBuilder().setLabel('second option label').setValue('option_value_2'); const info1 = config.newSelectSingle() .setId('api_endpoint') .setName('Data Type') .setHelpText('Select the data type you\'re interested in.') .setAllowOverride(true) .addOption(option1) .addOption(option2); ``` ### Methods #### `addOption(optionBuilder)` Adds a new select option. * **Parameters** * `optionBuilder` (OptionBuilder) - A builder for an option. * **Return** * `SelectSingle` - This builder, for chaining. #### `setAllowOverride(allowOverride)` Enables overriding for this config entry. If set to `true`, data source creators have the option to enable this for report editors. * **Parameters** * `allowOverride` (Boolean) - Whether or not this config entry can be overridden in reports. * **Return** * `SelectSingle` - This builder, for chaining. #### `setHelpText(helpText)` Sets the help text for this configuration entry. * **Parameters** * `helpText` (String) - The helpText to set. * **Return** * `SelectSingle` - This builder, for chaining. #### `setId(id)` Sets the unique ID for this configuration entry. * **Parameters** * `id` (String) - The ID to set. * **Return** * `SelectSingle` - This builder, for chaining. #### `setIsDynamic(isDynamic)` Sets the dynamic status for this configuration entry. If a dynamic configuration entry is modified, subsequent configuration entries are cleared. * **Parameters** * `isDynamic` (Boolean) - The dynamic status to set. * **Return** * `SelectSingle` - This builder, for chaining. #### `setName(name)` Sets the display name for this configuration entry. * **Parameters** * `name` (String) - The name to set. * **Return** * `SelectSingle` - This builder, for chaining. ``` -------------------------------- ### Get Start Point Source: https://developers.google.com/apps-script/reference/slides/line Retrieves the coordinates of the line's start point. ```APIDOC ## getStart() ### Description Returns the start point of the line, measured from the upper-left corner of the page. ### Method `getStart()` ### Return Type `Point` ``` -------------------------------- ### getInstallationSource() Source: https://developers.google.com/apps-script/reference/script/script-app Gets the source from which the script was installed. This is useful for add-ons to understand their installation context. ```APIDOC ## getInstallationSource() ### Description Gets the source from which the script was installed. This is useful for add-ons to understand their installation context. ### Method `ScriptApp.getInstallationSource()` ``` -------------------------------- ### Run the Apps Script API Quickstart Source: https://developers.google.com/apps-script/api/quickstart/python Execute the Python quickstart script from your working directory. This will initiate the OAuth 2.0 authorization flow if no valid credentials exist. ```bash python3 quickstart.py ``` -------------------------------- ### Get Start Point Source: https://developers.google.com/apps-script/reference/slides Returns the start point of the line, measured from the upper-left corner of the page. ```APIDOC ## getStart() ### Description Returns the start point of the line, measured from the upper-left corner of the page. ### Method `getStart` ### Return Type `Point` ``` -------------------------------- ### Create a working directory Source: https://developers.google.com/apps-script/api/quickstart/go Create a new directory for your project. This is the first step in setting up your Go workspace. ```bash mkdir quickstart ``` -------------------------------- ### ParagraphStyle.getIndentStart() Source: https://developers.google.com/apps-script/reference/slides Gets the start indentation for paragraphs in a TextRange. ```APIDOC ## ParagraphStyle.getIndentStart() ### Description Returns the text start indentation for paragraphs in the `TextRange` in points, or `null` if there are multiple paragraph styles on the given text. ### Method `getIndentStart()` ### Return type `Number|null` ``` -------------------------------- ### Run Node.js Sample Source: https://developers.google.com/apps-script/api/quickstart/nodejs Execute the Node.js sample application from your working directory using the `node` command. The first execution will prompt for user authorization. ```bash node . ``` -------------------------------- ### getThreads(start, max) Source: https://developers.google.com/apps-script/reference/gmail/gmail-label Gets a range of threads marked with this label, specifying the starting index and the maximum number of threads to return. ```APIDOC ## getThreads(start, max) ### Description Gets a range of threads marked with this label. ### Method `getThreads(start, max)` ### Parameters #### Path Parameters - **start** (`Integer`) - Required - The index of the starting thread. - **max** (`Integer`) - Required - The maximum number of threads to return. ### Return `GmailThread[]` — An array of threads marked with this label. ### Authorization Scripts that use this method require authorization with one or more of the following scopes or appropriate scopes from the related REST API: * `https://mail.google.com/` ``` -------------------------------- ### Get the starting column of a range Source: https://developers.google.com/apps-script/class_range Returns the starting column index of the range within the spreadsheet. Requires Sheets API authorization. ```javascript const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheets()[0]; const range = sheet.getRange('B2:D4'); Logger.log(range.getColumn()); ``` -------------------------------- ### Python Quickstart for Google Apps Script API Source: https://developers.google.com/apps-script/api/quickstart/python This Python script demonstrates basic usage of the Apps Script API. It shows how to create a new script project, upload files to it, and log the script's URL. Ensure you have a 'credentials.json' file in your working directory. ```python """ Shows basic usage of the Apps Script API. Call the Apps Script API to create a new script project, upload a file to the project, and log the script's URL to the user. """ import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient import errors from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. SCOPES = ["https://www.googleapis.com/auth/script.projects"] SAMPLE_CODE = """ function helloWorld() { console.log("Hello, world!"); } """.strip() SAMPLE_MANIFEST = """ { "timeZone": "America/New_York", "exceptionLogging": "CLOUD" } """.strip() def main(): """Calls the Apps Script API.""" creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", SCOPES ) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.json", "w") as token: token.write(creds.to_json()) try: service = build("script", "v1", credentials=creds) # Call the Apps Script API # Create a new project request = {"title": "My Script"} response = service.projects().create(body=request).execute() # Upload two files to the project request = { "files": [ {"name": "hello", "type": "SERVER_JS", "source": SAMPLE_CODE}, { "name": "appsscript", "type": "JSON", "source": SAMPLE_MANIFEST, }, ] } response = ( service.projects() .updateContent(body=request, scriptId=response["scriptId"]) .execute() ) print("https://script.google.com/d/" + response["scriptId"] + "/edit") except errors.HttpError as error: # The API encountered a problem. print(error.content) if __name__ == "__main__": main() ``` -------------------------------- ### Create and Configure SelectSingle Source: https://developers.google.com/apps-script/reference/data-studio/select-single Demonstrates how to create a SelectSingle configuration object, add options to it, and set various properties like ID, name, help text, and override capability. ```javascript const cc = DataStudioApp.createCommunityConnector(); const config = cc.getConfig(); const option1 = config.newOptionBuilder().setLabel('option label').setValue('option_value'); const option2 = config.newOptionBuilder() .setLabel('second option label') .setValue('option_value_2'); const info1 = config.newSelectSingle() .setId('api_endpoint') .setName('Data Type') .setHelpText('Select the data type you\'re interested in.') .setAllowOverride(true) .addOption(option1) .addOption(option2); ``` -------------------------------- ### Get Calendar Event Start Time Source: https://developers.google.com/apps-script/reference/calendar/calendar-event Retrieves the start time of a specific calendar event. Requires authorization scopes for calendar access. ```javascript const calendar = CalendarApp.getCalendarById( 'abc123456@group.calendar.google.com', ); const event = calendar.getEvents( new Date('Feb 01, 2023 16:10:00'), new Date('Feb 01, 2023 16:25:00'), )[0]; const startTime = event.getStartTime(); console.log(startTime); ``` -------------------------------- ### Get All Keys from Script Properties Source: https://developers.google.com/apps-script/reference/properties/properties Gets all keys in the current `Properties` store. This example demonstrates setting multiple properties first, then iterating through and logging each key. ```javascript const scriptProperties = PropertiesService.getScriptProperties(); scriptProperties.setProperties({ cow: 'moo', sheep: 'baa', chicken: 'cluck', }); const keys = scriptProperties.getKeys(); Logger.log('Animals known:'); for (let i = 0; i < keys.length; i++) { Logger.log(keys[i]); } ``` -------------------------------- ### getProjectTriggers() Source: https://developers.google.com/apps-script/reference/script/script-app Gets all installable triggers associated with the current project and current user. ```APIDOC ## getProjectTriggers() ### Description Gets all installable triggers associated with the current project and current user. ### Return `Trigger[]` — An array of the current user's triggers associated with this project. ### Authorization Scripts that use this method require authorization with one or more of the following scopes: * `https://www.googleapis.com/auth/script.scriptapp` ### Request Example ```javascript Logger.log( `Current project has ${ScriptApp.getProjectTriggers().length} triggers.`, ); ``` ``` -------------------------------- ### Start Local Web Server Source: https://developers.google.com/apps-script/api/quickstart/js Start a local web server on port 8000 using http-server. This server will host your application and handle requests. ```bash npx http-server -p 8000 ``` -------------------------------- ### Get Start Connection Source: https://developers.google.com/apps-script/reference/slides Returns the connection at the beginning of the line, or null if there is no connection. ```APIDOC ## getStartConnection() ### Description Returns the connection at the beginning of the line, or `null` if there is no connection. ### Method `getStartConnection` ### Return Type `ConnectionSite|null` ``` -------------------------------- ### Run the Java Sample Source: https://developers.google.com/apps-script/api/quickstart/java Execute this command in your terminal to run the Java sample application. The first time, it will prompt for authorization. ```bash gradle run ``` -------------------------------- ### Macro Configuration Example Source: https://developers.google.com/apps-script/manifest/sheets Example of a macro object configuration, including a default shortcut, function name, and menu name. ```json { "defaultShortcut": "Ctrl+Alt+Shift+1", "functionName": "myFunction", "menuName": "My Macro" } ``` -------------------------------- ### getIndex() Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet Gets the sequential position of the sheet within its parent spreadsheet, starting from 1. ```APIDOC ## getIndex() ### Description Gets the position of the sheet in its parent spreadsheet. Starts at 1. ### Method ```javascript sheet.getIndex() ``` ### Return `Integer` — The position of the sheet in its parent spreadsheet. ### Authorization Scripts that use this method require authorization with one or more of the following scopes: * `https://www.googleapis.com/auth/spreadsheets.currentonly` * `https://www.googleapis.com/auth/spreadsheets` ``` -------------------------------- ### Get Single Cell Range by Row and Column Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet Use `getRange(row, column)` to get a range object representing a single cell. Row and column indexing starts at 1. ```javascript const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheets()[0]; // Passing only two arguments returns a "range" with a single cell. const range = sheet.getRange(1, 1); const values = range.getValues(); Logger.log(values[0][0]); ``` -------------------------------- ### Initialize Java Project with Gradle Source: https://developers.google.com/apps-script/api/quickstart/java Use Gradle to initialize a new basic Java project and create the necessary directory structure for your source and resources. ```bash gradle init --type basic mkdir -p src/main/java src/main/resources ``` -------------------------------- ### getActiveUserLocale() Source: https://developers.google.com/apps-script/reference/base/session Gets the language setting of the current user as a string—for example, `en` for English. ```APIDOC ## getActiveUserLocale() ### Description Gets the language setting of the current user as a string—for example, `en` for English. ### Method `getActiveUserLocale()` ### Return `String` — a string that represents the user's language setting ### Request Example ```javascript // Log the language setting of the person running the script. Logger.log(Session.getActiveUserLocale()); ``` ``` -------------------------------- ### Apps Script API Java Quickstart Source: https://developers.google.com/apps-script/api/quickstart/java This Java code demonstrates how to authenticate with the Apps Script API, create a new script project, upload JavaScript and JSON files, and log the project URL. Ensure you have a `credentials.json` file in your classpath and the necessary OAuth2 scopes configured. ```java import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.script.Script; import com.google.api.services.script.model.Content; import com.google.api.services.script.model.CreateProjectRequest; import com.google.api.services.script.model.File; import com.google.api.services.script.model.Project; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AppsScriptQuickstart { private static final String APPLICATION_NAME = "Apps Script API Java Quickstart"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; /** * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved credentials folder at /secret. */ private static final List SCOPES = Collections.singletonList("https://www.googleapis.com/auth/script.projects"); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; /** * Creates an authorized Credential object. * * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */ private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { // Load client secrets. InputStream in = AppsScriptQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } public static void main(String... args) throws IOException, GeneralSecurityException { // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Script service = new Script.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); Script.Projects projects = service.projects(); // Creates a new script project. Project createOp = projects.create(new CreateProjectRequest().setTitle("My Script")).execute(); // Uploads two files to the project. File file1 = new File() .setName("hello") .setType("SERVER_JS") .setSource("function helloWorld() {\n console.log(\"Hello, world!\");\n}"); File file2 = new File() .setName("appsscript") .setType("JSON") .setSource("{\"timeZone\":\"America/New_York\",\"exceptionLogging\":\"CLOUD\"}"); Content content = new Content().setFiles(Arrays.asList(file1, file2)); Content updatedContent = projects.updateContent(createOp.getScriptId(), content).execute(); // Logs the project URL. System.out.printf("https://script.google.com/d/%s/edit\n", updatedContent.getScriptId()); } } ``` -------------------------------- ### Serve 'Hello World' using ContentService Source: https://developers.google.com/apps-script/reference/content/content-service Publish a script as a web app to serve simple text content. The browser URL will differ from the script URL for security. ```javascript function doGet() { return ContentService.createTextOutput('Hello World'); } ``` -------------------------------- ### Get Data Source Formulas Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet Retrieves all data source formulas present on a specific sheet. The example shows how to get formulas from a sheet by name and log the first formula's content. ```javascript // Opens the spreadsheet by its ID. If you created your script from within a // Google Sheets file, use SpreadsheetApp.getActiveSpreadsheet(). // TODO(developer): Replace the ID with your own. const ss = SpreadsheetApp.openById('abc123456'); // Gets Sheet1 by its name. const sheet = ss.getSheetByName('Sheet1'); // Gets an array of the data source formulas on Sheet1. // To get an array of data source formulas for the entire spreadsheet, // replace 'sheet' with 'ss'. const dataSourceFormulas = sheet.getDataSourceFormulas(); // Logs the first data source formula in the array. console.log(dataSourceFormulas[0].getFormula()); ``` -------------------------------- ### Get the start date of an all-day event Source: https://developers.google.com/apps-script/class_calendarevent Retrieves the start date of an all-day event. This method throws an error if the event is not an all-day event. The returned date is in the script's time zone. ```javascript const calendar = CalendarApp.getDefaultCalendar(); const event = calendar.createAllDayEvent( 'My all-day event', new Date('May 16, 2023'), ); const startDate = event.getAllDayStartDate(); console.log(startDate); ``` -------------------------------- ### Setup Sample Environment for CSV Import Source: https://developers.google.com/apps-script/samples/automations/import-csv-sheets?hl=it This function sets up the necessary Google Drive folders and a primary spreadsheet for processing CSV files. It also creates sample CSV files and installs an automated trigger. Use this to prepare your environment for the CSV import automation. ```javascript /** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This file contains functions that set up the folders and sample files used to demo the application. * * Sample data for the application is stored in the SampleData.gs file. */ // Global variables for sample setup. const INCLUDE_SAMPLE_DATA_FILES = true; // Set to true to create sample data files, false to skip. /** * Runs the setup for the sample. * 1) Creates the application folder and subfolders for unprocessed/processed CSV files. * from global variables APP_FOLDER | SOURCE_FOLDER | PROCESSED_FOLDER * 2) Creates the sample Sheets spreadsheet in the application folder. * from global variable SHEET_REPORT_NAME * 3) Creates CSV files from sample data in the unprocessed files folder. * from variable SAMPLE_DATA in SampleData.gs. * 4) Creates an installable trigger to run process automatically at a specified time interval. */ function setupSample() { console.log(`Application setup for: ${APP_TITLE}`); // Creates application folder. const folderAppPrimary = getApplicationFolder_(APP_FOLDER); // Creates supporting folders. const folderSource = getFolder_(SOURCE_FOLDER); const folderProcessed = getFolder_(PROCESSED_FOLDER); console.log( `Application folders: ${folderAppPrimary.getName()}, ${folderSource.getName()}, ${folderProcessed.getName()}`, ); if (INCLUDE_SAMPLE_DATA_FILES) { // Sets up primary destination spreadsheet const sheet = setupPrimarySpreadsheet_(folderAppPrimary); // Gets the CSV files data - refer to the SampleData.gs file to view. const csvFiles = getCSVFilesData(); // Processes each CSV file. for (const file of csvFiles) { // Creates CSV file in source folder if it doesn't exist. if (!fileExists_(file.name, folderSource)) { const csvFileId = DriveApp.createFile( file.name, file.csv, MimeType.CSV, ); console.log(`Created Sample CSV: ${file.name}`); csvFileId.moveTo(folderSource); } } } // Installs (or recreates) project trigger installTrigger(); console.log(`Setup completed for: ${APP_TITLE}`); } /** * */ function setupPrimarySpreadsheet_(folderAppPrimary) { // Creates the report destination spreadsheet if doesn't exist. if (!fileExists_(SHEET_REPORT_NAME, folderAppPrimary)) { // Creates new destination spreadsheet (report) with cell size of 20 x 10. const sheet = SpreadsheetApp.create(SHEET_REPORT_NAME, 20, 10); // Adds the sample data headings. const sheetHeadings = getHeadings(); sheet .getSheets()[0] .getRange(1, 1, 1, sheetHeadings[0].length) .setValues(sheetHeadings); SpreadsheetApp.flush(); // Moves to primary application root folder. DriveApp.getFileById(sheet.getId()).moveTo(folderAppPrimary); console.log( `Created file: ${SHEET_REPORT_NAME} In folder: ${folderAppPrimary.getName()}.`, ); return sheet; } } /** * Moves sample content to Drive trash & uninstalls trigger. * This function removes all folders and content related to this application. */ function removeSample() { getApplicationFolder_(APP_FOLDER).setTrashed(true); console.log( `'${APP_FOLDER}' contents have been moved to Drive Trash folder.`, ); // Removes existing trigger if found. const projectTriggers = ScriptApp.getProjectTriggers(); for (let i = 0; i < projectTriggers.length; i++) { if (projectTriggers[i].getHandlerFunction() === HANDLER_FUNCTION) { console.log( `Existing trigger with handler function of '${HANDLER_FUNCTION}' removed.`, ); ScriptApp.deleteTrigger(projectTriggers[i]); } } } ``` -------------------------------- ### HTML Structure for Apps Script Quickstart Source: https://developers.google.com/apps-script/api/quickstart/js This HTML file sets up the basic structure for the Google Apps Script API quickstart, including buttons for authorization and sign-out, and a preformatted element to display content. It also includes necessary JavaScript for handling authentication and API calls. ```html Google Apps Script API Quickstart

Google Apps Script API Quickstart