線上書籍

Home

鐵人賽-Google Apps Script整合運用

Google雲的檔案、資料夾權限
  1. 一般存取權:限制、知道連結的任何人
  2. 角色:檢視者、加註者、編輯者
專案授權
  1. 至少要有「檢視」的權限
  2. 將試算表的網址 /edit#gid=0 => /copy
  3. 「檔案 / 建立副本」
  4. 例:「鐵人賽(錄影)
資料種類
  1. 標題
  2. 資料
    1. 所有資料:取得資料會是一個二維陣列型態,陣列索引第1筆為「0」,但在試算表則為「2」,故差值為 2 
    2. 流水號資料:需要用它來計算最大值
取得標題列
  1. rowIndex = 1
  2. getSheetValues( startRow,  startColumn,  numRows,  numColumns)
    startRow:起始列的位置
    startColumn:起始欄的位置
    numRows:資料列數
    numColumns:資料欄數 
    https://developers.google.com/apps-script/reference/spreadsheet/sheet?hl=zh-tw#getsheetvaluesstartrow,-startcolumn,-numrows,-numcolumns
  3. 取得標題列 /*======================================== 取得標題列 =========================================*/ function get_head_custom() { let ss = SpreadsheetApp.getActiveSpreadsheet() let ws = ss.getSheetByName('day2'); let head_custom = ws.getSheetValues(1, 1, 1, ws.getLastColumn())[0]; console.log(head_custom); return head_custom; }

     

取得資料
  1. 必須判斷是否有資料,若 getLastRow() < 2 則 無資料,請返回 [] 
  2. 資料從 rowIndex = 2 開始,須扣掉 標題列,numRows - 1
  3. 取得資料 /*======================================== 取得資料 =========================================*/ function get_data_custom() { let ss = SpreadsheetApp.getActiveSpreadsheet() let ws = ss.getSheetByName('day2'); if (ws.getLastRow() < 2) return [];//無資料 let data_custom = ws.getSheetValues(2, 1, ws.getLastRow() - 1, ws.getLastColumn()); console.log(data_custom); return data_custom; }

     

  4. 結果:如圖 陣列索引 與 工作表列指標,剛好 差 2
  5. 取得流水號的最大值
    除了用「getSheetValues()」,也可以用 「getRange」再取值「getValues()」
    getRange:參數只給前面2個=>取得一格資料、前面3個=>取得一欄資料、全部4個=>所有資料
    Math.max.apply(Math, colArray);//在嵌套數組展開並找到其中的最大值
      /*======================================== 返回流水號 最大值+1 =========================================*/ function maxSn() { let ss = SpreadsheetApp.getActiveSpreadsheet() let ws = ss.getSheetByName('day2'); let colIndex = 1; if (ws.getLastRow() < 2) return 1;//尚無資料,返回1 let colArray = ws.getRange(2, colIndex, ws.getLastRow() - 1).getValues();//getSheetValues(2, colIndex, ws.getLastRow() - 1, 1) console.log(colArray); let maxi = Math.max.apply(Math, colArray);//在嵌套數組展開並找到其中的最大值 console.log(maxi); return maxi + 1; }

    這個函式,留到後面正式要「新增記錄」,再來調用

https://youtu.be/8iLme4ZI6Dc