Gastips

Linking Cloud Platform Project to Google Apps Script Project

Gists Introduction At April 8, 2019, the specification of Google Apps Script Project was changed. You can see this at Google Cloud Platform Projects. The official document says as follows. Warning: Starting on or after April 8, 2019, the Google Cloud Platform Console won’t be able to access the default GCP projects created for new Apps Script projects. Older, existing scripts may have default GCP projects that are still accessible, however.

GAS Library - GetEditType

Overview GetEditType is a GAS library for retrieving the edit types of the OnEdit event trigger of Spreadsheet using Google Apps Script (GAS). Description In the case that the OnEdit event trigger (simple and installable triggers) is used at Spreadsheet, when users manually edited the cell of Spreadsheet, the trigger is fired. At this time, there is the case that I want to know the edit type. For example, I would like to know about the following edit types.

Fixing Value Putting by Custom Function of Spreadsheet using Google Apps Script

Gists This is a sample script for fixing a value putting by a custom function of Spreadsheet using Google Apps Script. When a custom function is used, the value retrieved by the custom function of Spreadsheet is automatically updated by recalculating. So in the case that the value retrieved by the custom function is changed by the time, the value is also changed by automatically updating. In this sample script, I would like to introduce a method for fixing such values.

Retrieving Values with and without Duplicating from JSON Object using Google Apps Script

Gists This is a sample script for retrieving the values with and without duplicating from JSON object using Google Apps Script. Also this can be used by Javascript. Sample script var obj = [ { key1: "value1a", key2: "value1b" }, { key1: "value2a", key2: "value2b" }, { key1: "value5a", key2: "value5b" }, { key1: "value3a", key2: "value3b" }, { key1: "value1a", key2: "value1b" }, { key1: "value4a", key2: "value4b" }, { key1: "value5a", key2: "value5b" }, { key1: "value3a", key2: "value3b" } ]; var res = obj.

Creating New Table and Putting Values to Cells using Google Docs API with Google Apps Script

Gists This is a sample script for creating new table and putting values to cells using Google Docs API with Google Apps Script. Unfortunately, in the current stage, although I had been looking for the method for creating a table and putting the values in each cell at the official document, I couldn’t find. Google Docs API is growing now. So such documents might be not prepared yet. By this situation, I investigated about the method for achieving this method.

Possibility of Real Time Processes In a Cell on Spreadsheet using Google Apps Script

Gists This is a sample script for investigating the possibility of the real time processes in a cell on Google Spreadsheet using Google Apps Script. As a sample situation, it tried the real time clock in a cell on Google Spreadsheet using Google Apps Script. Demo: Usage: When you use this script, please do the following flow. Copy and paste the following script to the script editor (the container-bound script of Spreadsheet).

Deleting Pages of Google Document using Google Apps Script

Gists This is a sample script for deleting pages of Google Document from the last page using Google Apps Script. There are no methods for directly deleting pages of Google Document. This is one of several workarounds. In this workaround, the following flow is used. Flow Retrieve paragraphs in the body of Document. Retrieve elements in each paragraph. The page break is included in the paragraph. Delete elements from last page in order.

Retrieving Total Page of Google Document using Google Apps Script

Gists This is a sample script for retrieving total page of Google Document using Google Apps Script. There are no methods for directly retrieving the total page of Google Document. This is one of several workarounds. In this workaround, the total page is retrieved by converting to PDF format. var n = DriveApp.getFileById(id) .getBlob() .getDataAsString() .split("/Contents").length - 1; Logger.log("totalPages: %s", n); When you use this, please set the Google Document ID as id.

Processing Duplicated Rows of 2 Dimensional Arrays using Google Apps Script

Gists Overview These are sample scripts for processing the duplicated rows of 2 dimensional arrays using Google Apps Script. Description When I use Google Spreadsheet and/or see Stackoverflow, I sometimes see the situation which is required to process the duplicated rows of 2 dimensional arrays. I thought that when the sample scripts for it have already prepared, they will be useful for other users including me. So I published this post.

Specification of Google Apps Script Project was Changed at April 8, 2019

Gists At April 8, 2019, the specification of Google Apps Script Project was changed. Various specification was changed. Please see the detail at Google Cloud Platform Projects. Here, I would like to introduce one change which might be useful for users. The official document says as follows. When you enable an advanced service for your script project in the Apps Script editor, it is automatically enabled in the default GCP project when the script project is saved.

Backup Project as zip File using Google Apps Script

Gists This is a sample script for backing up a project as a zip file. When you use this script, please install a GAS library of ProjectApp2. You can back up both the standalone script type and the container-bound script type. In this script, the blob of zip file can be retrieved from ProjectApp2. So you can also send it as email without creating a file. var projectId = "### fileId of project ###"; var blob = ProjectApp2.

Split Array by n Elements using Google Apps Script

Gists This is a sample script for splitting an array by n elements using Google Apps Script. Sample script 1: var limit = 3; var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var res = []; while (ar.length > 0) res.push(ar.splice(0, limit)); Logger.log(res); // [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0]] Above sample script is a simple. But at Google Apps Script, the process cost of “while” is higher than the for loop as shown in this report.

Overwriting Several Google Documents by 2 Text Files using Google Apps Script

Gists This is a sample script for overwriting several Google Documents by 2 text files using Google Apps Script. Before you run this sample script, please install a GAS library of FetchApp. As a sample situation, it supposes to overwrite 2 existing Google Documents by 2 text files using the method of files.update Drive API v3. In the current stage, the batch request of Drive API cannot use the file media.

Creating Google Document by Converting PDF and Image Files with OCR using Google Apps Script

Gists This is a sample script for creating Google Document by converting PDF and image files with OCR using Google Apps Script. Before you run this sample script, please install a GAS library of FetchApp. function sample() { var fileId = "### fileId of PDF file and image files ###"; var metadata = { name: "sampleDocument", // Filename of created Google Document mimeType: MimeType.GOOGLE_DOCS // MimeType of Google Document }; var fileBlob = DriveApp.

GAS Library - FetchApp

Overview This is a GAS library for creating and requesting the type of multipart/form-data using Google Apps Script. This library enhances Class UelFetchApp of Google Apps Script. Description In order to fetch data from URL, there is Class UrlFetchApp in Google Apps Script. As the method for fetching, there is the method of fetch(url, params). In the current stage which was released this library, when user want to request with the type of multipart/form-data, the request body is required to be created by the user.

Converting Many Files to Google Docs using Google Apps Script

Gists This is a sample script for converting a lot of files to Google Docs (Spreadsheet, Document and Slides). Batch request can be used for converting files. In this sample script, the files are converted using the batch request. Batch request can request 100 API by one API call. This sample script uses the fetchAll method. So even if there are over 100 files, this script can process them.

Limitations for Inserting Images to Google Docs

Gists When an image is inserted to Google Docs (Spreadsheet, Document and Slides) using the method of insertImage using Google Apps Script, there is the case that the error occurs. The error messages are “server error” and “invalid image data”. Here, I would like to introduce the limitations for inserting images to Google Docs. As the result, it was found that the limitation is due to both the mimeTypes and the area of image rather than the file size.

Deleting Positioned Images on Google Document using Google Apps Script

Gists This is a sample script for deleting the positioned images on Google Document using Google Apps Script. In the current stage, unfortunately, there are no methods for deleting the positioned images in Class PositionedImage, yet. But when Google Docs API is used, the positioned images can be deleted. When you use this script, please enable Google Docs API at Advanced Google Services and API console. You can see how to enable them at here

Modify Searched Text to Small Capital Letters using Google Apps Script

Gists This is a sample script for modifying the searched text to the small capital letters using Google Apps Script. Unfortunately, in the current stage, there are no methods for modifying the part of texts to the small capital letters in Document Service, yet. But when Google Docs API is used, this can be achieved. When you use this script, please enable Google Docs API at Advanced Google Services and API console.

GAS Library - GistChecker

Overview This is a GAS library for notifying the change of number of comments, stars and forks of own Gists as an email using Google Apps Script. Description Recently, I noticed that when a comment was posted to own Gists, and the numbers of stars and forks of own Gists were changed, the notification mail is not sent. Also I knew that in the current stage, there are no official methods for notifying them, yet.

Communities for Google Apps Script

Gists Consumer (personal) version of Google+ is closed on April 2, 2019. By this, Apps Script community of Google+ is also closed. This is one of important communities for discussing. So in this post, I would like to introduce the other communities related to Google Apps Script. As the next community of Apps Script community of Google+, Google Apps Script Community was launched. This is also introduced at How to get help of official site like this.

Parsing Query Parameters from URL using Google Apps Script

Gists This is a sample script for parsing query parameters from an URL using Google Apps Script. Also this can be used at Javascript. The process cost becomes a bit lower than that of the script using the regular expression. Sample script function parseQuery(url) { var query = url.split("?")[1]; if (query) { return query.split("&") .reduce(function(o, e) { var temp = e.split("="); var key = temp[0].trim(); var value = temp[1].trim(); value = isNaN(value) ?

Modify Shading Color of Paragraph on Google Document using Google Apps Script

Gists This is a script for modifying the shading color of paragraph on Google Document using Google Apps Script. Recently, by releasing Google Docs API, the shading color got to be able to be modified using the script. Here, I would like to introduce a sample script for modifying the shading color of the paragraph on Google Document. At the current Document Service, the shading color cannot be modified yet.

Adding Title of vAxis to Embedded Chart on Spreadsheet using Google Apps Script

Gists When a chart is created by using EmbeddedChartBuilder of Spreadsheet service, the title of vAxis which is put by setOption("vAxis", {title: "y axis"}) doesn’t work. It is considered that this is a bug. Because I have confirmed that this had worked fine. Ref But this specification had been changed. So I would like to introduce the method for adding the title of vAxis when a chart is created using Google Apps Script.

tarUnarchiver for Google Apps Script

Overview This is a script for extracting files from a tar file using Google Apps Script. This script was created by native Google Apps Script. The following 3 situations gave me the motivarion for creating this script. Although I had been looking for the script for extracting files from a tar file from before, I have still not been able to find it. Unfortunately, there are no methods for extracting the files from the tar file in Google Apps Script.

Updated: GAS Library - ProcessApp

ProcessApp was updated to v1.0.1. v1.0.1 (February 10, 2019) New method of getExecutionTimeOfProcessType() was added. This method retrieves the total execution time of all functions by filtering the process type. For example, the total execution time of Web Apps can be retrieved. You can see the detail information here https://github.com/tanaikech/ProcessApp

GAS Library - ProcessApp

Overview This is a library for retrieving the process and information of Google Apps Script. Methods getExecutionTimeOfTrigger() : This method retrieves the total execution time of all functions executed by the time-driven trigger at owner’s account. For example, you can know the total execution time of all functions executed by the time-driven trigger in 24 h. getDevUrl() : This method retrieves the endpoint of developer mode for Web Apps like https://script.

Creating One-time Writing Cells using Google Apps Script

Gists This sample script is for creating one-time writing cells using Google Apps Script. At first, it supposes the following situation. A Spreadsheet is shared with users. The owner of Spreadsheet is you. After users put a value to a cell, you don’t want to make users edit the cell again. Namely, you want to protect the cell. This sample script achieves above situation. Preparation Before you use this script, please do the following flow.

Update: Taking advantage of Web Apps with Google Apps Script

“Taking advantage of Web Apps with Google Apps Script” was updated. A section of “How to use dev mode from outside” was added. When you deploy Web Apps, you can see the link labeled latest code. The link is like https://script.google.com/macros/s/###/dev. When you access to the link of latest code using your browser under you login to Google, you can access to Web Apps with the dev mode. But if you want to access to Web Apps with the dev mode from outside, there are no documents for the method.

Opening Dialog Box during Calculation and Retrieving Calculated Result using Google Apps Script

Gists When it starts a calculation, open a dialog box. When the calculation is finished, close the dialog and retrieve the calculated result. This is a sample script for achieving above flow. This sample script supposes to use the container-bound script of Spreadsheet. When you use this, please run the function of run(). Sample script: function doSomething(e) { // Scripts for calculating. Utilities.sleep(3000); // This is a sample wait time.

Closing Existing Sidebar using Google Apps Script

Gists This is a sample script for closing the existing sidebar using Google Apps Script. When the sidebar is opened, in order to close the sidebar, the sidebar can be closed by running google.script.host.close() with the script of sidebar. This is the general case. If you want to close the opened sidebar, such functions are not prepared. So I thought this workaround. The flow of this workaround is as follows.

Uploading Multiple Files From Local To Google Drive using Google Apps Script

Gists This is a sample script for uploading multiple files from local PC to Google Drive using Google Apps Script. The dialog, sidebar and Web Apps can be used as the GUI interface. Sample 1 In this sample, the following flow is run. Select files at browser. Upload the files every file. Save each file in Google Drive. When you use this, please copy and paste the Google Apps Script and HTML to the script editor, and run the HTML using the dialog, sidebar and Web Apps.

Summarizing Slides as Thumbnails

Gists This is a sample script for summarizing Slides as thumbnails. For example, it supposes a Slides including 15 pages. When this script is run, it summarizes 6 pages to one page as images. I created this because there are no methods for directly achieving this. This is useful for myself. If this is also useful for you, I’m glad. The flow of this workaround is as follows. Flow: Copy the original Slides file as a temporary file.

Retrieving Access Token for Service Account using Google Apps Script

Gists This is a sample script for retrieving the access token for Service Account using Google Apps Script. The flow for using this script is as follows. At first, please create the Service Account and retrieve JSON file. Put Scopes, private_key and client_email to the script. Run the script. var private_key = "#####"; // private_key of JSON file retrieved by creating Service Account var client_email = "#####"; // client_email of JSON file retrieved by creating Service Account var scopes = ["https://www.

Benchmark: Reading and Writing Spreadsheet using Google Apps Script

Gists Benchmark: Reading and Writing Spreadsheet using Google Apps Script October 12, 2018 Published. October 18, 2018 Updated. In order to compare with Advanced Google Service, a result of Sheets API by UrlFetchApp was added to Appendix. Kanshi Tanaike Introduction Please be careful! This result can be only used for Google Apps Script. There are a limit executing time for Google Apps Script (GAS). That is 6 minutes for Consumer and Google Apps free edition, and 30 minutes for G Suite and Early Access.

GAS Library - ArrangeStackingOrder

Overview ArrangeStackingOrder is a GAS library for arranging the stacking order of page elements on Google Slides using Google Apps Script (GAS). Demo This is a demonstration of this library when this is used as a Google Slides Addon. Description Do you have situations that you want to arrange the stacking order of page elements on Google Slides using GAS? I had it before. At that time, I could achieve it by creating a simple script.

Asynchronous Processing using Event Triggers

Gists September 21, 2018 Published. Kanshi Tanaike Overview This is a report about the possibility of asynchronous process using event triggers. This is for Google Apps Script (GAS). Description onEdit() which is a simple trigger is often used as a trigger when the values are modified on Spreadsheet. When users want to use the script including some methods which are required to be authorized as the onEdit event, a installable trigger of onEdit is used.

Expanding A1Notations using Google Apps Script

Gists This is a sample script for expanding a1Notations using Google Apps Script (GAS). In this script, for example, “A1:E3” is expanded to “A1, B1, C1, D1, E1, A2, B2, C2, D2, E2, A3, B3, C3, D3, E3”. When each cell in “A1:E3” is checked, this script might be able to be used. If this was useful for your situation, I’m glad. Script: function expandA1Notation(a1Notations) { var columnToLetter = function(column) { var temp, letter = ''; while (column > 0) { temp = (column - 1) % 26; letter = String.

GAS Library - DownloadLargeFilesByUrl

Overview DownloadLargeFilesByUrl is a GAS library for downloading large files from URL to Google Drive using Google Apps Script (GAS). Description I had been thinking of about whether a large file from an URL can be downloaded to Google Drive using GAS. When I have tried to download such large files, I noticed the following limitations. These limitations are due to the specification of GAS. When users download a file from URL using GAS, at the most users, it retrieves the blob using UrlFetchApp.

Replacing Text to Image for Google Document using Google Apps Script

Gists This is a sample script for replacing text to image for Google Document using Google Apps Script (GAS). There is a method for replacing text to text at Class Text of DocumentApp. But there are not methods for replacing text to image. So I created this sample script. Demo : This sample image was created by k3-studio. Usage : replaceTextToImage(body, replaceText, image, width); body : body of document.

Upload Files to Google Drive using Javascript

Gists This is a sample script for uploading files to Google Drive using Javascript. The files are uploaded by Drive API v3. gapi.client.drive.files.create() can create an empty file on Google Drive. But it cannot directly upload files including contents. I think that this might not be able to upload files and metadata with the multipart/related, although this might be resolved by the future update. So now, as one of workarounds, I use using XMLHttpRequest.

Benchmark: Decreasing Loop for Array Processing using Google Apps Script

Gists Benchmark: Decreasing Loop for Array Processing using Google Apps Script August 11, 2018 Published. Kanshi Tanaike Introduction Please be careful! This result can be only used for Google Apps Script. There are a limit executing time for Google Apps Script (GAS). That is 6 minutes. 1 So users always have to pay attention to reducing the process cost of the scripts. Especially, it is very important to know the process cost for the array processing, because the array processing is often used for spreadsheet and Google APIs.

Retrieving Screen Shots of Sites using Google Apps Script

Gists This is a sample script for retrieving screen shots of sites using Google Apps Script. In order to retrieve the screen shot, here, I used PageSpeed API. When you use this, please copy and paste the following script, and set an URL you want to retrieve a screen shot. var siteUrl = "### URL you want to retrieve a screen shot. ###"; var url = "https://www.googleapis.com/pagespeedonline/v4/runPagespeed?screenshot=true&fields=screenshot&url=" + encodeURIComponent(siteUrl); var res = UrlFetchApp.

GAS Library - RangeListApp

Overview RangeListApp is a GAS library for retrieving, putting and replacing values for Spreadsheet by a range list with a1Notation using Google Apps Script (GAS). Description There is Class RangeList as one of classes for Spreadsheet. There is setValue(value) in Class RangeList as a method. setValue(value) puts value to the cells of range list. Recently, when I used this method, I noticed that the following situations what I want cannot be achieved.

Notifying with email when Netatmo was down

Overview This is a Google Apps Script for notifying with email when Netatmo was down. Description I’m measuring the surrounding environment using Netatmo. There were little that my Netatmo was down so far. But recently, my Netatmo is sometimes down. It is considered that the reason is due to the thermal runaway, because the recent Japan is very hot. When Netatmo was down, users can know it by logging in using the browser and/or running the mobile application.

Retrieve Last of Specific Row and Column

Gists This is a sample script for retrieving the last coordinate of the specific row and column. When the methods of getLastRow() and getLastColumn() of Class Range for Spreadsheet are used, the last coordinates of the vertical and horizontal data range can be retrieved. When users want to retrieve the last coordinates of each row and column, there are no methods. So I created this script. I think that there are several scripts for this situation.

Notifying Comments at Stackoverflow by Email using Google Apps Script

This is a script for sending an email when users got comments at Stackoverflow. I had wished I could get an email when I got a comment at Stackoverflow. Although I investigated about this, it seems that I can get the email every 3 hours. For this situation, I wished I could get it much earlier. I thought that this can be achieved using GAS and Stack Exchange API. So I created this script.

Adding Query Parameters to URL using Google Apps Script

Gists This is for adding the query parameters to the URL. This sample script is prepared by ES5. So this can be also used for Javascript. When I created an endpoint with some query parameters, I had used the scripts of various patterns every time. Today, I prepared this sample script to unify them. If this is also useful for you, I’m glad. Sample script : String.prototype.addQuery = function(obj) { return this + Object.

Benchmark: Conditional Branch using Google Apps Script

Gists Benchmark: Conditional Branch using Google Apps Script July 11, 2018 Kanshi Tanaike Introduction Please be careful! This result can be only used for Google Apps Script. There are a limit executing time for Google Apps Script (GAS). That is 6 minutes.1 So users always have to pay attention to reducing the process cost of the scripts. Especially, it is very important to know the process cost for the array processing, because the array processing is often used for spreadsheet and Google APIs.

Updated: GAS Library - ManifestsApp

ManifestsApp was updated to v1.0.3. v1.0.3 (July 11, 2018) By Google’s update, “sheets” was added to manifests for installing the configuration of Macro. By this, this library was updated. You can see the added methods (getSheets(), setSheets()) at Usage. If you set “sheets”, please put the value of “sheets” as the resource like below sample. {"macros": [{"menuName": "QuickRowSum", "functionName": "calculateRowSum"}]} Don’t put {"sheets": {"macros": [{"menuName": "QuickRowSum", "functionName": "calculateRowSum"}]}} You can check this at https://github.

Limitation of Images for Inserting to Spreadsheet using Google Apps Script

Gists Introduction Here I would like to introduce about the limitation of images for inserting to Spreadsheet using Google Apps Script (GAS). When you want to insert the images to Spreadsheet using GAS, insertImage() of class Sheet is usually used for this situation. At this time, an error sometimes occurs. This indicates that there is the limitation for inserting images to Spreadsheet. So I investigated the limitation. As a result, it was found that the limitation depends on the image area (pixels^2) rather than the file size of it.

Taking Advantage of Google Apps Script (Tanaike's list)

Here, CLI tools, libraries, Add-ons, Reports, Benchmarks and Sample Scripts for taking advantage of Google Apps Script which are publishing in my blog, Gists and GitHub are summarized. If these are useful for you, I’m glad. You can check this at https://github.com/tanaikech/taking-advantage-of-google-apps-script.

Retrieving Number of Lines of Google Document

Gists There are no prepared methods for retrieving the number of lines in the Google Document. So I thought this workaround. If the end of each line can be detected, the number of lines can be retrieved. So I tried to add the end markers of each line using OCR. At Google Documents, when a sentence is over the page width, the sentence automatically has the line break. But the line break has no \r\n or \n.

Benchmark: Search for Array Processing using Google Apps Script

Gists Benchmark: Search for Array Processing using Google Apps Script July 2, 2018 Kanshi Tanaike Introduction Please be careful! This result can be only used for Google Apps Script. There are a limit executing time for Google Apps Script (GAS). That is 6 minutes.1 So users always have to pay attention to reducing the process cost of the scripts. Especially, it is very important to know the process cost for the array processing, because the array processing is often used for spreadsheet and Google APIs.

Resumable Conversion from CSV File with Large Size (> 50 MB) to Several Spreadsheets by Splitting File

Gists Overview This is a sample script which can achieve the resumable conversion from the large CSV-file to several spreadsheets by splitting the CSV file using Google Apps Script (GAS). Description Is there a situation that you want to convert a CSV file with the large size (> 50 MB) to Spreadsheet? When such large CSV file is converted to Spreadsheet, you will experience the error. The reason is the size and/or also it may be due to the total cells (> 2,000,000 cells) of CSV file.

Cryptopia API for Google Apps Script

Gists By the Google’s update at June 19, 2018, finally, Utilities.computeDigest(), Utilities.computeHmacSha256Signature() and Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Script, the result can be retrieved without using jsSHA. So Cryptopia API can be created using only Google Apps Script. If this is useful for you, I’m glad. Sample script : When you use this, at first, please input the requiring values.

About Updated Utilities.computeHmacSignature()

Gists By the Google’s update at June 19, 2018, finally, Utilities.computeDigest(), Utilities.computeHmacSha256Signature() and Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Script, the result can be retrieved without using jsSHA. When I used the updated them, the response speed is much faster than that of jsSHA. It is considered that this may be optimized for Google Apps Script. As a sample, it shows 2 samples as follows.

GAS Library - FilesApp

Overview FilesApp is a GAS library for retrieving file and folder list in Google Drive using Google Apps Script (GAS). Also this can create a tree from all files and folders in Google Drive. Description When I create some applications using Google Drive, there are often the case which is required to retrieve the file list and folder list. I had prepared the script each time for each case so far.

Retrieving Reformatted Scripts without Comments in a Project using Google Apps Script

Gists Overview This is a sample script for easily retrieving the reformatted scripts without comments in a project using Google Apps Script (GAS). Description When I create GAS script, if the format of script is not correct, the script editor lets me know about it. By this, I can find that the script editor and/or Google Drive checks the format of scripts. I had wished if I could use this function.

Remove Third-party Apps with Account Access using Google Apps Script

Gists Overview This is a method for removing Third-party Apps with Account Access using a script. Demo Description When users create a script in a project and run the script, if the methods which are required to use scopes are included, users have to authorize to use the scopes using the browser. By authorizing it, users can use the script. The authorized projects can be seen at Third-party Apps with Account Access.

Resumable Upload for Web Apps using Google Apps Script

Overview This is a sample script for uploading files with large size (> 50 MB) at Web Apps using Google Apps Script (GAS). The resumable upload method is used for uploading files. This script can be also applied to the script using gapi of javascript. Demo This is a demonstration of this script. As a demonstration, it uploads a file with the size of 100 MB to my Google Drive.

Retrieve Difference Between 2 Dimensional Arrays using Google Apps Script

Gists This sample script retrieves the difference elements between 2 dimensional arrays using Google Apps Script. In Google Apps Script, 2 dimensional arrays are often used at Google Docs and Google APIs. And from my recent report, it has already found that the process cost of filter() is the lowest in the other loop methods. So I use the script like this. var ar1 = [["a1", "b1", "c1"], ["a2", "b2", "c2"], ["a3", "b3", "c3"], ["a4", "b4", "c4"], ["a5", "b5", "c5"]]; var ar2 = [["a2", "b2", "c2"], ["a5", "b5", "c5"], ["a1", "b2", "c3"]]; var res = ar1.

GAS Library - BatchRequest

Overview This is a library for running Batch Requests using Google Apps Script (GAS). Description When users use Google’s APIs, one quota is used for one API call. When the batch request is used, several APIs can be called by one quota, although there are some limitations in the batch request. For example, in GAS, Drive API can be used be DriveApp. In this case, the quota is not used for using Drive API.

CLEAN method for Google Apps Script

Gists This is a sample script which works the same action with the CLEAN method of VBA. The CLEAN method of VBA removes the characters of 0-31, 127, 129, 141, 143, 144, 157. Although I had looked for such method for Google Apps Script, I couldn’t find it. So I created this. If this is useful for you, I’m glad. function cleanForGAS(str) { if (typeof str == "string") { var escaped = escape(str.

Taking advantage of Web Apps with Google Apps Script

Overview This is a report to take advantage of Web Apps with Google Apps Script (GAS). Description There is Web Apps as one of applications using Google Apps Script (GAS). I sometimes use this Web Apps. But I have only a little the information for the specification of Web Apps. So in order to take more advantage of Web Apps, I investigated and summarized about this. The aim of this report is to become one of the basic information for creating various applications using Web Apps with GAS.

Retrieves All Named Ranges in Spreadsheet as a1Notation

Gists This is a sample script for Google Apps Script (GAS). This script retrieves all named ranges in Spreadsheet. The names and range of the retrieved named ranges are output as the keys and the values of JSON object, respectively. The sample output is {"name1": "Sheet1!A1:B2", "name2": "Sheet2!B1:C2",,,}. The name of named range has to be only one in the spreadsheet. This was used. Sheets.Spreadsheets.get() of Sheets API can retrieve all named ranges.

GAS Library - RunAll

Overview This is a library for running the concurrent processing using only native Google Apps Script (GAS). Description Have you ever thought about the concurrent processing using only native Google Apps Script (GAS)? So far, I had run the concurrent processing using golang, javascript and python. But the script cannot be used by the trigger event, because these are not native GAS. Recently, it was found that the fetchAll method added by the Google’s update at January 19, 2018 is worked by the asynchronous processing.

Benchmark: fetchAll method in UrlFetch service for Google Apps Script

Gists By Google’s update at January 19, 2018, fetchAll method was added to the UrlFetch service. When I saw the usage, I couldn’t find the detail information about the actual running state. So I investigated about it. As the result, it was found that the fetchAll method is worked by the asynchronous processing. The returned data is reordered by the order of requests. By this, it was also found that if you want to retrieve the data from the several URL, the process cost of UrlFetchApp.

Benchmark: Loop for Array Processing using Google Apps Script

Gists Benchmark: Loop for Array Processing using Google Apps Script April 16, 2018 Published. July 26, 2018 Updated. Result of reduce was added. Kanshi Tanaike Introduction Please be careful! This result can be only used for Google Apps Script. There are a limit executing time for Google Apps Script (GAS). That is 6 minutes.1 So users always have to pay attention to reducing the process cost of the scripts.

Benchmark: Event Objects for Google Apps Script

Gists Introduction There are event objects at Google Apps Script. Typically, users which use Spreadsheet often use onEdit(event). Here, I would like to introduce the process costs for the event objects using this onEdit(event). When onEdit(event) is used for the spreadsheet, event of onEdit(event) has the following structure. { "authMode": {}, "range": { "columnStart": 1, "rowStart": 1, "rowEnd": 1, "columnEnd": 1 }, "source": {}, "oldValue": "old sample text", "user": { "nickname": "sampleName", "email": "sample email" }, "value": "sample text" } In this structure, for example, the range of active cell is "range": {"columnStart": 1, "rowStart": 1, "rowEnd": 1, "columnEnd": 1 }.

Unicode normalization using Google Apps Script

Overview This is a script for converting strings from NFD (Normalization Form Decomposition) to NFC (Normalization Form Composition) using Google Apps Script. Description Here, I would like to introduce a script for the unicode normalization using Google Apps Script. There are the characters with ゙ which is the voiced dot and the characters with ゚ which is the semi-voiced dot in Japanese language. When these are used for some applications,

Transposing JSON Object using Google Apps Script

Gists This is a sample script for transposing JSON object using Google Apps Script. Input data : [ {"key1":"a1","key2":"a2","key3":"a3","key4":"a4","key5":"a5"}, {"key1":"b1","key2":"b2","key3":"b3","key4":"b4","key5":"b5"}, {"key1":"c1","key2":"c2","key3":"c3","key4":"c4","key5":"c5"}, {"key1":"d1","key2":"d2","key3":"d3","key4":"d4","key5":"d5"}, {"key1":"e1","key2":"e2","key3":"e3","key4":"e4","key5":"e5"} ] Output data : { "key1": ["a1", "b1", "c1", "d1", "e1"], "key2": ["a2", "b2", "c2", "d2", "e2"], "key3": ["a3", "b3", "c3", "d3", "e3"], "key4": ["a4", "b4", "c4", "d4", "e4"], "key5": ["a5", "b5", "c5", "d5", "e5"] } Script : At first, keys have to be defined by yourself, because the order of json is not decided.

Open Site with New Window using Google Apps Script

Gists This is a sample script for opening a site with new window using Google Apps Script. It is possible to open the site inside the opened dialog box using iframe. But in my situation, I had to open the site as new window. So I created this. As a sample application, it can think of like this. When the special keyword was inputted, open sites and files in Google Drive as a help window.

Adding a Label to a Message using Message ID for Gmail

Gists These are sample scripts for adding a label to a message using message ID for Gmail. Sample 1 This sample adds a label to a thread using message ID. In this case, all messages in the thread have the label. Even if it adds a label to a message in the thread using addLabel(), all messages in the thread have the label, becauce addLabel can only be used for the thread.

How to Retrieve Replied Emails for Gmail

Gists Description : This sample script is for retrieving emails which replied for received mails. Because there are no samples which confirm whether the owner (me) replied to the received mails, I created this. The point is as follows. When there are more than 2 messages in a thread, there might be a possibility to have replied. For more than 2 messages in a thread The email address of “from” for the 1st message is the sender’s address.

Updated: GAS Library - ManifestsApp

ManifestsApp was updated to v1.0.2. v1.0.2 (January 29, 2018) ProjectApp2 is published, and got to be able to use both standalone script type and container-bound script type. By this, this library also got to be able to be used for the both projects. For this update, please enable Apps Script API. Please check “How to install”. You can check this at https://github.com/tanaikech/ManifestsApp.

GAS Library - ProjectApp2

Overview This is a GAS project library for Google Apps Script (GAS). This library can be used for the projects of both standalone script type and container-bound script type. Description There are Class SpreadsheetApp and Class DocumentApp for operating spreadsheet and document, respectively. But there is no Class for operating GAS project. If there is such Class ProjectApp, GAS project can be directly operated by GAS script. I thought that this will lead to new applications, and created ProjectApp.

Copying and Overwriting GAS Project

Gists Pattern 1 This is a sample script for copying GAS project to a container-bound script of Google Docs (Spreadsheet, Document and Form (and Slides)). The project is created as a new project. In order to use this sample, please do the following installation flow. If you use this sample script, at first, please test using a new project and new Google Docs. By this, please understand the work of this script.

Batching Requests for Google Apps Script

Gists There is the bathing requests in the Google APIs. The bathing requests can use the several API calls as a single HTTP request. By using this, for example, users can modify filenames of a lot of files on Google Drive. But there are limitations for the number of API calls which can process in one batch request. For example, Drive API can be used the maximum of 100 calls in one batch request.

Zaif API for Google Apps Script

Gists This sample script is for using Zaif API by Google Apps Script. The following go script is a sample at Zaif API. package main import ( "fmt" "time" "strconv" "crypto/hmac" "crypto/sha512" "io/ioutil" "net/http" "encoding/hex" "net/url" "strings" ) var key = "<your_key>" var secret = "<your_secret>" func main() { uri := "https://api.zaif.jp/tapi" values := url.Values{} values.Add("method", "get_info") values.Add("nonce", strconv.FormatInt(time.Now().Unix(), 10)) encodedParams := values.Encode() req, _ := http.NewRequest("POST", uri, strings.NewReader(encodedParams)) hash := hmac.

Bittrex API for Google Apps Script

Gists This sample script is for using Bittrex API by Google Apps Script. The following PHP script is a sample at bittrex.com. $apikey='xxx'; $apisecret='xxx'; $nonce=time(); $uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce; $sign=hash_hmac('sha512',$uri,$apisecret); $ch = curl_init($uri); curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign)); $execResult = curl_exec($ch); $obj = json_decode($execResult); When this is converted to GAS, the script is as follows. function main() { var apikey = '#####'; // Please input your key. var apisecret = '#####'; // Please input your secret.

Binance API for Google Apps Script

Gists This sample script is for using Binance API by Google Apps Script. This script encryptes “signature” like samples. In this script, “Example 1: As a query string” is used, and it retrieves “All orders (SIGNED)” by “GET”. function main() { var key = '#####'; // Please input your key. var secret = '#####'; // Please input your secret. var api = "/api/v3/allOrders"; // Please input API Endpoint you want. var timestamp = Number(new Date().

Add-on - ShapeApp

ShapeApp for Google Slides was published as an add-on application When you use Google Slides, have you ever thought about creating and updating shapes on Slides by inputting parameters, and arranging selected shapes? I have thought about them. Recently, since Class SlidesApp was added to GAS, it came to be able to easily to create various applications for Slides. So I created this. This application is add-on application which was made of GAS.

Which of Drive API v2 or v3 is used for DriveApp.searchFiles()

Gists Experiment It has investigated the differences between the documents of “Search for Files” for v2 and v3. The following table shows the comparison of v2 and v3 for “Valid fields for files.list”. The column of DriveApp.searchFiles() means whether the query can be used for DriveApp.searchFiles(). v2 v3 Difference DriveApp.searchFiles() title name different v2: succeed, v3: fail fullText fullText same mimeType mimeType same modifiedDate modifiedTime same lastViewedByMeDate viewedByMeTime different v2: succeed, v3: fail trashed trashed same starred starred same parents parents same owners owners same writers writers same readers readers same sharedWithMe sharedWithMe same properties properties same properties with visibility=‘PRIVATE’ appProperties different v2: succeed, v3: fail visibility visibility same Result As the result, it is considered that DriveApp.

Bitfinex API for Google Apps Script

Gists This sample script is converted this sample script (javascript) to Google Apps Script. The point for converting is signature as shown in the following sample script. At Bitfinex API, after "/api/" + apiPath + nonce + rawBody is encrypted using HMAC SHA-384, the data of byte array is converted to HEX. In Google Apps Script, there is no the method for this. The data which was encrypted by Utilities.

Automatic Recalculation of Custom Function on Spreadsheet

Gists In this report, I would like to introduce a workaround for automatically recalculating custom functions on Spreadsheet. 1. Situation The sample situation is below. This is a sample situation for this document. There are 3 sheets with “sheet1”, “sheet2” and “sheet3” of sheet name in a Spreadsheet. Calculate the summation of values of “A1” of each sheet using a custom function. Sample script of the custom function is as follows.

Add-on - RearrangeScripts

RearrangeScripts was published as an add-on application Recently, I have reported RearrangeScripts for rearranging scripts in a GAS project. At that time, I got messages and mails from many developers. They said that you should publish this as an add-on. So, this was released. Now you can search “RearrangeScripts” as an add-on for Spreadsheet. If this is helpful for you, I’m happy. Add-on GitHub Demo

Difference Between Given Values and Retrieved Values for Shapes on Google Slides

Gists This is a document for explaining the difference between given values and retrieved values for shapes on Google Slides. When a shape is created to a slide using Slides API, most users give the size of height and width as pt. When the size is retrieved from the created shape as pt, the size is often difference from the given size. For example, when a square shape is created by giving the height and width of 100 pt, the size which is retrieved from the created square becomes 99.

Retrieving ClientId using Google Apps Script

Gists This is a sample script for retrieving clientId using Google Apps Script. var accessToken = ScriptApp.getOAuthToken(); var url = "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=" + accessToken; var params = { method: "post", headers: {"Authorization": "Bearer " + accessToken} }; var res = UrlFetchApp.fetch(url, params).getContentText(); var clientId = JSON.parse(res).azp; Logger.log(clientId)

Downloading File Using Button of Dialog Box on Google Docs

Gists This is a sample script for downloading a file using a button of dialog box on Google Docs (Spreadsheet, Document and Slides). Please use this sample script at script editor on Google Docs (Spreadsheet, Document and Slides). And please set file ID in the script. FLow : The flow of this sample script is as follows. Run dialog(). Open a dialog. When users click a download button, retrieve file ID at GAS side.

Rearranging Files in GAS Project (Restricted)

Gists Introduction Recently, I have introduced a GAS library and a CLI tool for rearranging files in GAS project. Those are RearrangeScripts and ggsrun. Because today, I found a new way for rearranging files, I would like to introduce it although there is a restriction. By the recent Google-update, users become able to create folders in GAS project. The new way uses this. At first, please see the demonstration GIF animation.

Retrieving Instance of User-Interface Environment

Gists This sample script is for retrieving an instance of user-interface environment for Spreadsheet, Document and Slides. When I create applications which use user interface (for example, sidebar, dialog and so on), the user interface can be used for Spreadsheet, Document and Slides. If the application doesn’t use the methods depend on Spreadsheet, Document and Slides, this script can give 3 choices to users. function getUi() { var ui; try { ui = SpreadsheetApp.

Mixing 2 Array Objects Included Dictionary Object by Javascript

Gists This is a sample script for combining and mixing 2 objects. Each object is an array which included a dictionary type. When the key of the dictionary object is the same, the values are mixed. This can be also used for Google Apps Script. Input var obj1 = [ {"key1": ["value1a1", "value1a2"]}, {"key1": ["value1aa1", "value1aa2"]}, {"key2": ["value2a1", "value2a2"]}, {"key3": ["value3a1", "value3a2"]}, ]; var obj2 = [ {"key1": ["value1b1", "value1b2"]}, {"key3": ["value3b1", "value3b2"]}, {"key3": ["value3bb1", "value3bb2"]}, {"key4": ["value4b1", "value4b2"]}, ]; Output [ {"key1": ["value1a1", "value1a2", "value1b1", "value1b2", "value1aa1", "value1aa2"]}, {"key2": ["value2a1", "value2a2"]}, {"key3": ["value3a1", "value3a2", "value3b1", "value3b2", "value3bb1", "value3bb2"]}, {"key4": ["value4b1", "value4b2"]} ] Sample script : Javascript : function mixture(obj1, obj2) { Array.

Taking Advantage of Manifests by GAS Library

Gists Introduction By recent Google update (Google update at October 24, 2017), various new winds to GAS developers were blown. There is “Manifests” as one of the new winds. “Manifests” makes us manage the project using JSON. Especially, the special scopes which have to use OAuth2 process can be used by only setting them to the Manifests. I think that this is the largest modification. However, when scopes are added to a project using Manifests, users who use the project can use only added scopes.

Retrieving Size of Tables in Google Slides using Google Apps Script

Gists This sample script is for retrieving the size (width and height) of a table in Google Slides using Google Apps Script. There are no methods for directly retrieving the table size using SlidesApp yet. So I thought of a workaround using Slides API. When the slide information is retrieved using Slides.Presentations.Pages.get() of Slides API, the information of tables is also included. In the information, the height and width of table are also included.

SlideApp for Google Slides

Gists By recent Google updated, Class SlideApp is added to Google Slides. SlideApp will be bring a lot of applications. Here, I would like to introduce 2 samples. 1. Sidebar function showSidebar() { var html = HtmlService .createHtmlOutput('Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />') .setTitle('My custom sidebar') .setWidth(300); SlidesApp.getUi().showSidebar(html); } 2. Copy slides in existing Slide to a new Slide This sample script create a new Slide with slides you want to copy.

GAS Library - RearrangeScripts

Overview This is a GAS application for rearranging Google Apps Scripts (GAS) in a project which can be seen at the script editor. Description Have you ever thought about rearranging Google Apps Scripts in a project which can be seen at the script editor? I also have thought about it. Finally, I could find the workaround to do it. And recently, I have given this function to ggsrun which is a CLI tool.

GAS Library - ZipFolder

Overview This is a library for zipping a folder using Google Apps Scripts. Description When users manually download a folder on Google Drive, users can download all files in the folder as a zip file using the web interface. There are zip tools in Class Utilities of Google Apps Script. However, the zip tools cannot create a zip file from a folder. And it cannot retrieve all files included any folders in a folder.

GAS Library - ManifestsApp

Overview This is a Manifests library for Google Apps Scripts. Description By recent update of Google, Manifests was added to Google Apps Script Project. At the moment I saw the detail, I thought that this Manifests will blow a new wind for a lot of GAS developers. So I created this. This library makes users easily access Manifests using Google Apps Script. If this was useful for you, I’m glad.

GAS Library - ProjectApp

Overview This is a GAS project library for Google Apps Script (GAS). Description There are Class SpreadsheetApp and Class DocumentApp for operating spreadsheet and document, respectively. But there is no Class for operating GAS project. If there is the Class ProjectApp, GAS project can be directly operated by GAS script. I thought that this will lead to new applications, and created ProjectApp. On the other hand, as a CLI tool for operating GAS project, there has already been ggsrun.

Uploading Local Files to Google Drive without Authorization using HTML Form

Gists This is a sample script for uploading local file to Google Drive without the authorization using HTML form. A selected file in your local PC using HTML form is uploaded to Google Drive and saved to Google Drive. When you use this, at first, please deploy Web Apps. The script is doPost() of following scripts. Script : Google Apps Script function doPost(e) { var data = Utilities.base64Decode(e.parameters.data); var blob = Utilities.

Measuring Execution Time of Built-In Functions for Google Spreadsheet

Gists This sample script is for measuring the execution time of built-in functions for Google Spreadsheet. Unfortunately, there are not measurement tools for retrieving the execution time of built-in functions. So I thought of about a workaround. Flow : Import a value to a cell. The value is anything good, because this is used as a trigger. Please do this by yourself. Custom functions cannot use setValue(). So I used onEdit().

Straightening Elements in 2 Dimensional Array using Google Apps Script

Gists This sample script is for straightening elements in 2 dimensional array using Google Apps Script (GAS). When applications using Spreadsheet are developed by GAS, it usually uses 2 dimensional array by setValues(). And the lengths of each element are required to be the same. On the other hand, data used for the applications might not be the same length for each element in 2 dimensional array. This sample script can be used under such situation.

Enhanced onEdit(e) using Google Apps Script

Gists onEdit(e) which is used for the Edit event on Spreadsheet has the old value as e.oldValue. The specifications for this are as follows. When an user edited a “A1” cell from “hoge” to “fuga”, e of onEdit(e) shows hoge for e.oldValue and fuga for e.value. When an user edited “A1:A2” cell from “hoge” to “fuga”, e.oldValue and e.value of onEdit(e) are not shown anything. When an user copied and pasted from other cell, e.

Selecting Files in Google Drive using Select Box for Google Apps Script

Gists This is a sample script for selecting files in Google Drive using HTML select box for Google Apps Script. Feature Feature of this sample. It is a simple and space saving. When the folder is selected, the files in the folder are shown. When the file is selected, the ID of file is retrieved. Users can use this ID at GAS. When a folder is opened, all files in the folder are cached.

Uploading Image Files to Slack Using Incoming Webhooks by Google Apps Script

Gist This sample script is for uploading image files to Slack using Incoming Webhooks by Google Apps Script. When users try to upload image files to Slack using Incoming Webhooks, it has been known that although the access token is required to directly upload them, Incoming Webhooks can upload them by using the tag of image_url. In this sample script, it uploads image files (BMP, GIF, JPEG and PNG) on Google Drive to Slack using Incoming Webhooks.

Retrieving Files with Filename Included Special Characters using Google Apps Script

Gists This sample script is for retrieving files with filename included special characters using Google Apps Script. The files are used on Google Drive. The files with filename of special characters cannot be retrieved using DriveApp.getFilesByName(). This workaround solved this. As a query parameter, name contains 'filename with special characters' is used. This contains is very important. name='filename with special characters' cannot retrieve such files. Today, it was found that name contains 'filename with special characters' is the workaround.

Retrieving Spreadsheet ID from Range using Google Apps Script

Gists This is a sample script for retrieving spreadsheet ID from a range using Google Apps Script. I sometimes want to retrieve spreadsheet ID from ranges. In such case, I always use this. Range -> Retrieve Sheet using getSheet() -> Retrieve Spreadsheet using getParent() -> Retrieve spreadsheet ID var id = "123456789abcdefg"; var sheet = "Sheet"; var cells = "a1:b10"; var range = SpreadsheetApp.openById(id).getSheetByName(sheet).getRange(cells); var id = range.getSheet().getParent().getId(); >>> id ---> 123456789abcdefg

Retrieving Values By Header Title for Spreadsheet

Gists This is a sample script for retrieving values by header title for Spreadsheet. This is created by Google Apps Script. The main script is as follows. Main script : When the instance is retrieved, all data of the sheet is analyzed. So when the each value is retrieved, the speed is fast. function GetValueByKey(sheetname) { return new getValueByKey(sheetname); }; (function(r) { var getValueByKey; getValueByKey = (function() { getValueByKey.name = "getValueByKey"; function getValueByKey(sheetname) { var alldata, e, header, ss; try { ss = SpreadsheetApp.

Updated: GAS Library - OnedriveApp

OnedriveApp was updated to v1.0.2. Moved the instance of PropertiesService.getScriptProperties() to outside of this library. When there is the PropertiesService.getScriptProperties() inside the library, it was found that the parameters that users set was saved to the library. So this was modified. I’m sorry that I couldn’t notice this situation. GitHub of OnedriveApp

Changing Values by Checking Duplicated Values of JSON for Javascript

Gists This sample script is for changing values by checking duplicated values of JSON for Javascript. Please see the following script. There is an array with a JSON data with 3 keys and 3 values. It is found that the values for each element duplicate. These duplicated values are changing by adding numbers. I use this for managing filenames. This script also can be used for Google Apps Script. If this was useful for you, I’m glad.

Updated: GAS Library - ImgApp

ImgApp was updated to v1.2.0. New method was added. 3. updateThumbnail() Overview This method is for updating thumbnail of files on Google Drive using images you selected. Description For example, zip files don’t have the thumbnail on Google Drive. An icon is shown as the thumbnail. For the most files, Google Drive can create automatically each thumbnail. But there are sometimes files which cannot be created the thumbnail. Zip file is also one of them.

GAS Library - OnedriveApp

This is a library of Google Apps Script for using Microsoft OneDrive. Feature This library can carry out following functions using OneDrive APIs. Retrieve file list on OneDrive. Delete files and folders on OneDrive. Create folder on OneDrive. Download files from OneDrive to Google Drive. Upload files from Google Drive to OneDrive. Demo You can see the detail information here https://github.com/tanaikech/OnedriveApp

Interconversion Between Google Docs and Microsoft Docs

Gists This sample script is for the interconversion between Google Docs (document, spreadsheet and presentation) and Microsoft Docs (word, excel and powerpoint). The feature is to convert them without Advanced Google Services. Since Advanced Google Services is not used for this, if you publish your script with this script, you are not necessary to explain how to install Advanced Google Services. This script converts between Google Docs and Microsoft Docs using UrlFetchApp.

Retrieving Access Token From OneDrive using Google Apps Script

Gist Overview This GAS sample is for retrieving access token to use OneDrive APIs using Google Apps Script. In this script, the authorization code is automatically retrieved. Demo Usage In order to use this, both accounts of Google and OneDrive (MSN) are required. Google side Copy and paste the sample script to your script editor. You can use the standalone script for this. Deploy Web Apps. On the Script Editor File -> Manage Versions -> Save New Version Publish -> Deploy as Web App -> At Execute the app as, select “your account” -> At Who has access to the app, select “Only myself” -> Click “Deploy” -> Copy URL of “latest code” (This is important!

Converting a1Notation to GridRange for Google Sheets API

Gists When it uses Google Sheets API v4, GridRange is used for it as the range property. These sample scripts are for converting from a1Notation to GridRange. You can chose from following 2 scripts. Both scripts can retrieve the same result. Script 1 : This is from me. function a1notation2gridrange1(sheetid, a1notation) { var data = a1notation.match(/(^.+)!(.+):(.+$)/); var ss = SpreadsheetApp.openById(sheetid).getSheetByName(data[1]); var range = ss.getRange(data[2] + ":" + data[3]); var gridRange = { sheetId: ss.

Multipart-POST Request Using Google Apps Script

Gist These sample scripts are for requesting multipart post using Google Apps Script. In most cases, the multipart request is used for uploading files. So I prepared 2 sample situations as follows. For each situation, the request parameters are different. Upload a file from Google Drive to Slack. Convert an excel file to Spreadsheet on Google Drive using Drive API v3. Multipart post is required for these situations.

Retrieving Images on Spreadsheet

Gist This is a sample script for retrieving images on Spreadsheet. Unfortunately, there are no methods for retrieving directly images on spreadsheet using GAS. So I use the method which retrieves URL from =image(URL) and retrieves the image from the URL. In this case, =image(URL) has to be in the cell. Images embedded by insertImage() cannot be retrieved. At first, please confirm them. Sample script : var cell = "A1"; // Cell address with the function of "=image()" var filename = "samplename"; // Output filename var image = SpreadsheetApp.

Retrieving Array Coordinates of Duplicated Elements

This sample is for retrieving array coordinates of duplicated elements. Script : var inputdata = ["a", "b", "b", "c", "d", "c", "e", "a", "f", "g"]; var dic = {}; var result = []; inputdata.forEach(function(e, i){ if (dic[e]) { result[i] = 'Duplicated'; } else { result[i] = null; } dic[e] = "temp"; }); Logger.log(JSON.stringify(result)) Logger.log([i for (i in result) if(result[i]=='Duplicated')]) Result : [null,null,"Duplicated",null,null,"Duplicated",null,"Duplicated",null,null] [2, 5, 7]

Get File List Under a Folder on Google Drive

Gists This is a sample of Google Apps Script. This script is for retrieving all files and folders under a folder on Google Drive. All files and folders in the specific folder can be retrieved. If you want to retrieve file list with all files and folders on Google Drive, please use DriveApp.getRootFolder().getId() as folderId. When there are a lot of files in the folder, it may be over the limitation time to execute script.

Pseudo Browser with Google Spreadsheet

Gist Overview This is a sample script for creating the pseudo browser using Google Spreadsheet. Description I unexpectedly noticed this. I think that this is for off-line browsing using HTML data. So there are many limitations. At first, please confirm them. Limitations It cannot move from opened site to other outside site. If the outer site is opened as a new wind, your own browser is opened and move there.

Downloading Files From Google Drive Under No Authorization Using Browser

Gist This is a sample script for downloading files from Google Drive under no authorization using browser. By using this sample, you can make other users download files from your Google Drive. Even if the other users are not Google users, they can download the files. Demo This is a demonstration for downloading files from Google Drive under no authorization using browser. From the top document, You can see that an user who is not owner of Google Drive is downloading files.

Updated: GAS Library - ImgApp

ImgApp was updated to v1.1.0. New method was added. 2. doResize() Overview This method is for resizing images. Description Unfortunately, there are no methods to resize images at Google Apps Script. As a workaround, there is a method that it imports the image in Google Document and resizes the image using setWidth() and setHeight(). But in this method, the resized blob cannot be retrieved. So although I had thought of other workaround, I had not been able to find it.

GAS Library - ImgApp - getSize()

1. getSize() Overview This method is for retrieving the width and height of image as the unit of pixel. Description Unfortunately, there are no methods to directly retrieve the image size at Google Apps Script. As a workaround, there is a method that it imports the image in Google Document and retrieves the size using getWidth() and getHeight(). But in this method, it uses much time and resources on Google.

Retrieving Access Token for Google APIs

Gists This sample is for retrieving access token for Google APIs. I created this for studying newStateToken(). Preparation In order to use this sample, please do as follows. Deploy and launch Web Apps for retrieving redirect uri On the Script Editor File -> Manage Versions -> Save New Version Publish -> Deploy as Web App -> At Execute the app as, select “your account” -> At Who has access to the app, select “Only myself” -> Click “Deploy” -> Click “latest code” (By this click, it launches the authorization process.

Updated: GAS Library - SOUWA

SOUWA means summing in Japanese. SOUWA can sum string elements in an array at the high speed. The speed of SOUWA with the pyramid algorithm is about 380 times faster than that of the standard method. New algorithm for summing array elements was developed for SOUWA. You can see the detailed report of this library at here. If you are interested in this, I’m glad. It was updated to v1.0.2. Please check it out.

Search Route and Embedding Map using Custom Function on Spreadsheet

This sample script is for searching route between place A and B and embedding a map by custom function on Spreadsheet. I think that this method is one of various ideas. Problem When the map is embedded to a cell on spreadsheet as an image, the function =IMAGE() is suitable for this situation. However, Class Maps, setFormula() for importing =IMAGE() and DriveApp.createFile() for creating images from maps also cannot be used for custom functions.

Giving and Retrieving Parameters for Chart at GAS

This sample script is for retrieving parameters from a chart. The chart created by both Google Apps Script and manually operation can be used. Creates Chart When a chart is created, it supposes following parameters. var parameters = { "title": "x axis", "fontName": "Arial", "minValue": 0, "maxValue": 100, "titleTextStyle": { "color": "#c0c0c0", "fontSize": 10, "fontName": "Roboto", "italic": true, "bold": false } }; .setOption('hAxis', parameters) Retrieve Parameters From Chart For the chart created by above parameters, in order to retrieve the parameters, it uses following script.

Benchmark: Effect of Comprehension for GAS

Description There are a limit executing time for Google Apps Script (GAS). It’s 6 minutes. So users have to pay attention to the process cost of the script. GAS can use JavaScript 1.7. This means to be able to be used comprehension for GAS. In this report, the process cost for the comprehension has been investigated. The normal for loop was used as the competitor. As a result, it was found that the comprehension can be used one of methods for reducing the process cost.

Embedding Animation GIF in A Cell on Spreadsheet

This sample script is for embedding animation GIF in a cell using custom function on Spreadsheet. I think that this method is one of various ideas. Problem There are some limitations. Images of jpeg and png can be embedded in a cell using =IMAGE(). But when animation GIF is embedded using it, GIF is not played. insertImage() can insert the animation GIF to sheet. But it is not imported to one cell.

OCR using Custom Function on Spreadsheet

This sample script performs OCR and imports resultant text to a cell using custom function on Spreadsheet. Drive API has a function to do OCR. It was used for this sample. I think that this method is one of various ideas. Problem When OCR is performed and imported the result to a cell on spreadsheet, there are some limitations. DriveApp, UrlFetchApp, setFormula() cannot be used for custom functions. Solution In order to avoid these limitations, I used Web Apps.

Retirving All files in Folder with Spreadsheet

This sample retrieves all files in a folder with spreadsheet. When there are some folders in the folder with spreadsheet, this script can retrieve all files in all folders. This script has to be a container-bound script for spreadsheet. Script : function getFileList(){ var folderlist = (function(folder, folderSt, results){ var ar = []; var folders = folder.getFolders(); while(folders.hasNext()) ar.push(folders.next()); folderSt += folder.getId() + "#_aabbccddee_#"; var array_folderSt = folderSt.split("#_aabbccddee_#"); array_folderSt.pop() results.

Embedding a Map to a Cell using Custom Function on Spreadsheet

This sample script embeds a map to a cell using custom function on Spreadsheet. I think that this method is one of various ideas. Problem When the map is embeded to a cell on spreadsheet as an image, the function =IMAGE() is suitable for this situation. However, setFormula() for importing =IMAGE() and DriveApp.createFile() for creating images from maps also cannot be used for custom functions. Solution In order to avoid these limitations, I used Web Apps.

Embedding a Chart to a Cell using Custom Function on Spreadsheet

This sample script embeds a chart to a cell using custom function on Spreadsheet. I think that this method is one of various ideas. Problem When you want to create a chart and embed it to a cell using custom functions, you notice that insertChart() cannot be used. There are some limitations for using custom functions. But insertChart() creates floating charts. So in order to embed a chart to a cell, the function =IMAGE() is suitable for this situation.

Retrieving HTML File ID from Microsoft Docx File on Google Drive

This sample script converts from Microsoft Docx File on Google Drive to Google Spreadsheet, and converts to HTML file. Drive APIs v2 and v3 are used for this. Please set as follows. Drive API v2 Drive API v3 “Drive API v2” can be used at Google Apps Script by enabling Drive API of Advanced Google services and of Google API Console. How to use it is as follows.

Changing Line to Bars for Combo Chart using GAS

Sample data This is a sample data for this sample script. The column B was created by the normal distribution formula, and the column C was created by multiplying random number for column B. A, B, C 1.0, 0.0001, 0.0000 1.5, 0.0009, 0.0006 2.0, 0.0044, 0.0037 2.5, 0.0175, 0.0133 3.0, 0.0540, 0.0236 3.5, 0.1296, 0.0533 4.0, 0.2420, 0.0073 4.5, 0.3522, 0.2468 5.0, 0.3990, 0.0843 5.5, 0.3522, 0.3352 6.0, 0.2420, 0.

Sending E-mail When Spreadsheet was Edited from Outside by Sheet API

This sample script sends an e-mail, when spreadsheet was edited from outside by Sheet API v4. When you use this sample, please create a container bound script with spreadsheet which is edited by Sheet API. And please input your e-mail and run firstly a method of createTrigger(). By this, a trigger is installed as onChange(). After this, edit spreadsheet from outside by Sheet API v4. When when spreadsheet was edited from outside by Sheet API v4, I used sendEmail() as a sample, because script editor is closed.

Changing Slack Status using Google Apps Script

This script changes slack status using GAS. If you want to change it on time you decided, it can be achieved by installing this method as a trigger. In order to use this, the required scope is users.profile:write. function setSlackStatus(token, user, status_text, status_emoji) { return UrlFetchApp.fetch( 'https://slack.com/api/users.profile.set', { method: 'post', payload: { token: token, user: user, profile: JSON.stringify({status_text: status_text, status_emoji: status_emoji}) }, muteHttpExceptions: true } ).getContentText(); } function main() { var res = setSlackStatus( '### Your access token ###', '### User ID ###', 'sample', ':coffee:' ); Logger.

Retrieving User Information with Shared Spreadsheet

This sample script retrieves the user information which is editing the shared spreadsheet. It was found as follows. User information retrieving by Class Session is the owner and users which installed triggers by themselves. When each user installs a trigger, user information retrieving by Class Session losts the accuracy. So user information has to be retrieved using a temporally installed trigger. Using onOpen(), it cannot directly install triggers and authorize.

Overwriting Spreadsheet to Existing Excel File

This sample script converts a spreadsheet to excel file, and overwrites the excel file to the existing excel file. When you use this script, at first, please confirm whether Drive API is enabled at Google API console. Because the existing excel file is overwritten, the file name and file ID are not changed. function overWrite(src_spreadsheetId, dst_excelfileId) { var accesstoken = ScriptApp.getOAuthToken(); return UrlFetchApp.fetch( "https://www.googleapis.com/upload/drive/v3/files/" + dst_excelfileId + "?uploadType=multipart", { method: "PATCH", headers: {Authorization: "Bearer " + accesstoken}, contentType: "application/vnd.

Converting Spreadsheet to PDF

Converting Spreadsheet to PDF This sample script converts from a spreadsheet to a PDF file which has all sheets in the spreadsheet. When you use this, please enable Drive API at Google API console. var spreadsheetId = "#####"; var folderId = "#####"; var outputFilename = "#####"; DriveApp.getFolderById(folderId) .createFile(UrlFetchApp.fetch( "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf", { method: "GET", headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}, muteHttpExceptions: true }) .getBlob()) .setName(outputFilename);

GAS Library - CreateImg

Recently, I had been looking for creating an image from coordinate data. Unfortunately I have never found them. So I made this. This Google Apps Script (GAS) library creates an image file from coordinate data. You can see the detail information at https://github.com/tanaikech/CreateImg. There is a part where I would like to improve in this library. That’s convByteSlice(). I think that there is the method to be faster about the part.

Comprehension of GAS

Here, I would like to introduce a comprehension of GAS. Input : var data = [[[0], [1], [2], [3]], [[4], [5], [6], [7]]]; Output : [[0.0, 2.0], [0.0, 2.0]] Pattern 1 var a = []; for (var i=0; i<data.length; i++) { var temp = []; for (var j=0; j<data[i].length; j++) { if (data[i][j][0] % 2 == 0) temp.push(j); } a.push(temp); } Logger.log(a) Pattern 2 var b = []; data.

Creating Spreadsheet from Excel file

These scripts can be executed on Script Editor. But, in order to use these, you have to enable Drive API of Advanced Google services and of Google API Console. “Drive API v2” can be used at Google Apps Script by enabling Drive API of Advanced Google services and of Google API Console. How to use it is as follows. In the script editor, select Resources > Advanced Google services

Creating Downloaded Excel file as Spreadsheet

This is a sample GAS script to create an Excel file, which was downloaded from web, as Spreadsheet. By using Drive API, it can be achieved without access token. Script : function downloadFile(fileURL, folder) { var filename = fileURL.match(".+/(.+?)([\?#;].*)?$")[1]; var response = UrlFetchApp.fetch(fileURL); var rc = response.getResponseCode(); var blob = response.getBlob(); var resource = { "mimeType": "application/vnd.google-apps.spreadsheet", "parents": [{id: folder}], "title": filename }; var res = Drive.Files.insert(resource, blob); var fileInfo = [rc, res.

How to use "fields" of Drive APIs

There are a lot of APIs on Google. When we use Google Drive APIs, they usually have “fields” as a resource. The parameter “fields” gives various information which is selected to us. This is one of important parameters. And this can be used at Google Apps Script (GAS) although that version is v2. About how to use it, there are some documents. But it is difficult to find how to use it at GAS.

Retrieving File ID from File Name using GAS

This is a sample script of GAS for converting file name to file id on Google Drive. Drive API is used for this. So please enable Drive API at Advanced Drive Services and Google API Console. function nameToId(filename){ return [i.id for each (i in Drive.Files.list({q: "title='" + filename + "' and trashed=false"}).items)]; }

Download Files Without Authorization From Google Drive

Overview In this article, files can be downloaded without authorization. Description When we download files from Google Drive, it usually has to use Drive API. In order to use Drive API, access token is required. If you want to make your friends download files from your Google Drive, the authorization process is to take time. Also Web Link for each files can be used. But it has to set for each files.

Create Folder Tree on Google Drive

This is a sample script for creating a folder tree including all folders in Google Drive. For each element, parent folder and sub folder are retrieved. Script : var results = (function(folder, folderSt, results){ var ar = []; var folders = folder.getFolders(); while(folders.hasNext()) ar.push(folders.next()); folderSt += folder.getName() + "(" + folder.getId() + ")#_aabbccddee_#"; var array_folderSt = folderSt.split("#_aabbccddee_#"); array_folderSt.pop() results.push(array_folderSt); ar.length == 0 && (folderSt = ""); for (var i in ar) arguments.

Export CSV File from Spreadsheet and Make Download Button

This is a script to export a CSV file from spreadsheet and make an user download it. When the users download it, they can download by push a button made by this script. In order to use this script, put both HTML and script in a GAS project. html : This file name is “download.html”. <!DOCTYPE html> <html> <body> Download CSV? <form> <input type="button" value="ok" onclick="google.script.run .withSuccessHandler(executeDownload) .saveAsCSV();" /> </form> </body> <script> function executeDownload(url) { window.

Send E-mail with xlsx File Converted from Spreadsheet

This is a script to send e-mail with a xlsx file converted from spreadsheet as an attachment file. Access token is necessary to use this script. function excelSender() { var accesstoken = "[your accesstoken]"; var sheetID = "[sheet id]"; var xlsxName = "[output xlsx file name]" var params = { "headers" : {Authorization: "Bearer " + accesstoken}, "muteHttpExceptions" : true }; var dUrl = "https://www.googleapis.com/drive/v3/files/" + sheetID + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" var xlsxlFile = UrlFetchApp.

Send E-mail with Excel file converted from Spreadsheet

This sample script sends an e-mail with an Excel file exported from Spreadsheet as an attachment file. function excelSender() { var sheetID = [Sheet ID]; var xlsxName = [Excel file name]; var params = { "headers" : {Authorization: "Bearer [Retrieved AccessToken]"}, "muteHttpExceptions" : true }; var dUrl = "https://www.googleapis.com/drive/v3/files/" + sheetID + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" var xlsxlFile = UrlFetchApp.fetch(dUrl, params).getBlob().setName(xlsxName); MailApp.sendEmail({ to: [Mail address], subject: "sample subject", body: "sample body", attachments: [xlsxlFile] }); } Is ScriptApp.

Download a CSV File from Spreadsheet Using Google HTML Service

Here, I introduce how to download a CSV file from spreadsheet using Google HTML Service. Using “onOpen()”, it addes menu for launching a dialog. After launching the dialog, “getFileUrl()” is launched by pushing a button. “getFileUrl()” exports a CSV file and outputs download URL. The CSV file is downloaded by “executeDownload()”. Please put both HTML and GAS to a GAS project. HTML : download.

Making charts at spreadsheet

var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var chart = sheet.newChart() .setChartType(Charts.ChartType.LINE) .asLineChart() .addRange(sheet.getRange('a1:a21')) .addRange(sheet.getRange('b1:b21')) .addRange(sheet.getRange('c1:c21')) .setColors(["green", "red"]) .setBackgroundColor("black") .setPosition(5, 5, 0, 0) .setPointStyle(Charts.PointStyle.MEDIUM) .setOption('useFirstColumnAsDomain', true) .setOption('height', 280) .setOption('width', 480) .setOption('title', 'Sample chart') .setOption('hAxis', { title: 'x axis', minValue: 0, maxValue: 20, titleTextStyle: { color: '#c0c0c0', fontSize: 20, italic: false, bold: false }, textStyle: { color: '#c0c0c0', fontSize: 12, bold: false, italic: false }, baselineColor: '#c0c0c0', gridlines: { color: '#c0c0c0', count: 4 } }) .

Event of onEdit() for Google spreadsheet

About Event Objects For example, it thinks the situation of input text of ‘test’ to ‘A1’ on a sheet. When you use only ‘onEdit(e)’ without an installing trigger, ‘e’ has following parameters. {authMode=LIMITED, range=Range, source=Spreadsheet, user=, value=test} In this case, the event cannot send an e-mail because of ‘authMode=LIMITED’. When you use “onEdit(e)” with an installing trigger of “Edit”, ‘e’ has following parameters. {authMode=FULL, range=Range, source=Spreadsheet, value=test, triggerUid=#####} In this case, the event can send an e-mail because of ‘authMode=FULL’.

File upload using doPost on Google Web Apps

File upload using HTML form in GAS project Rule Following scripts have to be made into a project of Google Apps Script. Deploy the GAS project as a web application. Ref After updated the script, it has to be updated as a new version. Form.html : <html> <body> <form> <input type="file" name="imageFile"> <input type="button" value="ok" onclick="google.script.run.upload(this.parentNode)"> </form> </body> </html> GAS : function doGet() { return HtmlService.

Retrieving cells without blank using GAS

This is a sample script for retrieving cells without blank cells. Figure 1 shows the sample spreadsheet. In this sheet, the row 14 has one space. Fig. 1: Sample spreadsheet. Data is retrieved as follows. var data = SpreadsheetApp .getActiveSpreadsheet() .getActiveSheet() .getRange('a1:a30') .getValues(); 1. Retrieving cells with spaces and no blank cells.

GAS Library - SOUWA_GAS - Effects on Optimized Codes of Pyramid Method

Kanshi TANAIKE Abstract I have already reported that the pyramid method is one of very effectively algolithms for summing string elements in an array using Google Apps Script (GAS). This report describes the adaptability of the pyramid method to any languages except for GAS. c++ (g++), Go, Java, Javascript on Node.js, Python and Ruby were chosen as the sample languages. In those languages, there are languages which have the distinctive commands for summing the array elements.