Google Apps Script 是一種程式碼語言,語法類似 Javascript,開發者完全不需要準備開發工具,就可以擴展 Google Apps 建構類似巨集的效果,達到工作流程自動化的目標,也可以建立 Web 應用程式,整合 Google 協作工具。
為 Google 的文件、試算表、表單添加額外的小工具。
可以為 Google 試算表建立自動化腳本。
支援發布一個網頁應用程式,並嵌入 Google 協作平台中的應用程式。
支援與其他 Google 服務互動,包括 AdSense、Analytics、Calendar、Drive、Gmai、and Maps。
支援 Add-ons,用來擴展 Google 文件、試算表、簡報和表單之功能,也可將它們發佈到 Add-ons商店。
Google Apps Script 教學
使用 Google Apps Script 解決問題
客戶狀況前情提要:
1. 客戶使用 Google Sheets 完成前台頁面的變化。
2. Google Sheets 可以有個 API 讓 Wordprss 可以 request。
原先預想 運用 Google Sheets 可以直接用「發佈到網路」,如果這樣使用 ajax 引用的話會有 CORS 的問題。
主要不使用的原因是直接從 Google Sheets 下來的資料其實有太多不是我們想要的。如果直接使用 WordPress 做 request 的話,會額外花太多精力在清洗資料不能直接拿來用,所以最後決定使用Google Apps Script 來做 Google Sheet 的轉接。
記得注意版本問題
有些網路上會說:「透過 Google Sheet API 拿回來的資料預設會帶有 CORS Header,所以不受跨 domain 存取限制,很方便吧!」但僅限於舊版 Google Sheets 能這樣做,現在的版本都不行了。
I’ve confirmed that this is a bug in the Drive API, but it is only affecting the exportLinks for New Google Sheets file. Old Google Sheets and other Google file types should work correctly. I’ve raised it with the team, but it’s unclear how long it will take to fix. Unfortunately there are no simple workarounds, and the only solution would be to introduce a server-side component that would download the file and then pass it along to the client.
如果真的想要只用 Google Sheets 做 API 可以用 Tabletop javascript 來引入,就不會有 CORS 的問題了。Google Apps Script 在接 Google 相關服務其實都蠻方便的,比如說 Google Drive 或是 Google Calendar 等。
(2021/08/22更新)
前些日子用 Tabletop javascript(新版好像叫做 Papa parse) 或測試直接串 google excel (就是網路上用 google excel key 組出一個 url 的那種方式),發現此方法被 google 檔了,會有 CORS 的問題,但如果用 google app script 做轉接仍然會通
Google Apps Script 操作方法
Step 1 / 完成 Sheets 的編輯後,在雲端硬碟新增一個 Google Apps script,如果沒有就點擊「更多…」尋找。
用 Google Apps Script 不用 「發佈到網路」
Step 2 / Google Apps Script 是吃 doGet() 開始的
function doGet(e){
var ss = SpreadsheetApp.openByUrl(“google sheet 的 URL”);
var sheet = ss.getSheetByName(“該 sheet 的 name (下方該表單的名稱)”);
return getUsers(sheet);
}
function getUsers(sheet){
var jo = {};
var dataArray = [];
// 從地 3 橫排開始收集資料, 並從第一直排到最後橫排及最後直排
var rows = sheet.getRange(3,1,sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
for(var i = 0, l= rows.length; i<l ; i++){
var dataRow = rows[i];
var record = {};
record[‘secondary_category’] = dataRow[2];
record[‘name’] = dataRow[3];
dataArray.push(record);
}
jo.user = dataArray;
var result = JSON.stringify(jo);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
因為目前 Google Apps Script 並非 100% 支援 ES6 的語法,所以有寫還是要用舊語法來寫
Step 3 / 把 Google Apps Script 對外發佈。
發佈 → 部署為網路應用程式
Step 4 / 專案版本,點擊新增,選擇新增才會更新 Google Apps Script 的對外 API 資訊。