2018年3月28日 星期三

Google Apps Script 入門到進階(15) --- 操控 Google 文件寫記錄

近期要記錄在 Google 雲端執行程式的 Log,藉由 Google 文件與 Google Apps Script 來達成,以下記錄相關流程。
手動建立Google 文件,並取得文件的 ID。

建立 Google Apps Script 。

輸入以下 Script 進行操作。
function PrintLog() {
  var logID= "Google文件ID";
  log = new Doc(logID);
  log.print(getDateAndTimeOfNow() + " 記錄開始\n");
  log.print(getDateAndTimeOfNow() + " 大家好,這是GAS寫檔測試\n");  
  log.print(getDateAndTimeOfNow() + " 記錄結束\n");
}

Doc = function(id){
  this.ID = id;
  this.doc = DocumentApp.openById(this.ID); 
  this.body = this.doc.getBody();
  this.docText = this.body.editAsText();
}

Doc.prototype.print = function(str){
  this.docText.appendText(str);
}

function getDateAndTimeOfNow(){
  var now = new Date();
  var year = now.getYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();
  var hour = now.getHours();
  var min = now.getMinutes();
  var sec = now.getSeconds();
  var millisec = now.getMilliseconds();
  return (""+year) + ("0"+month).slice(-2) + ("0"+day).slice(-2) +'_'+ 
    ("0"+hour).slice(-2) + ("0"+min).slice(-2) + ("0"+sec).slice(-2) + ("0"+millisec).slice(-3);
}

執行,Google雲端會要你開啟檔案執行的權限。

選擇自己的帳戶。

點選進階。

前往指定檔案。

設定允許。

執行的結果,可在 Google 文件中看到。

參考資料: