Trying to post data from Google Spreadsheet to a external Api

前端 未结 1 1723
[愿得一人]
[愿得一人] 2021-02-06 19:37

I\'m using Google SpreadSheet and IFTTT to do a DB Call Log of my phone, this is working perfect. Now I\'m trying to populate a form in a web page by API from this DB Call Log.

相关标签:
1条回答
  • 2021-02-06 19:56

    Will try to answer the question one by one:

    1) Reformat date: You can use Utilities.formatDate() in apps script to modify your date.

    Code:

    function reformatDate(dtStr)
    {
     if (dtStr == undefined)
     dtStr = "April 1, 2017 at 01:54PM"
    
     dtStr = dtStr.replace("at", "") // Remove at
     dtStr = dtStr.replace(/(\d)(PM)/g,"$1 $2") //Add a space between the time and PM
     dtStr = dtStr.replace(/(\d)(AM)/g,"$1 $2") //Add a space between the time and AM
     Logger.log(dtStr)
    
     dtStr = new Date(dtStr)
     var newDt = Utilities.formatDate(dtStr, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm") 
     Logger.log(newDt)
    
     return newDt
    }
    

    2) Get last row Values: You can use getLastRow() and getValues() functions in apps scripts

    function lastRowData(){
     var ss = SpreadsheetApp.getActive()
     var sheet = ss.getActiveSheet()
     var lastRow = sheet.getLastRow() 
     var lastCol = sheet.getLastColumn()
     var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getValues()
     return lastRowData[0]
    
    }
    

    Edit

    To get values as is i.e. displayed values in the sheet, you can modify the getvalues to getDisplayValues() like so:

    var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getDisplayValues()
    

    3) Trigger your sheet: I will not reinvent the wheel here. But will provide you with an awesome answer from @Mogsdad Link: Trigger an email when a cell is written into from another app (IFTTT)

    In short, you will have to use onEdit Trigger to detect new entries.
    If on edit doesn't work, try on Change trigger.

    Complete code:

    function myFunction() {
    var lastRow = lastRowData()
    var data = {
    
        'department':     lastRow[0],
        'first_name' :    lastRow[1],
        'last_name' :     lastRow[2],
        'email' :         lastRow[3]',
        'phone' :         [lastRow[4]],
        'deadline' :      reformatDate(lastRow[5])
    }
    
    var payload = JSON.stringify(data)  
    
    var headers = {
    
         'AUTHORIZATION': 'Token b8473654v6345teryrby456yrtyrtyertytdvfh87afc',
         // Add any other required parameters for XXX API.
    };
    var url = 'http://api.XXX.com/api/1.0/clients/';
    var options = {
        'method': 'post',
        'contentType': 'application/json', 
        'headers': headers,
        'payload' : payload,
    };
    var response = UrlFetchApp.fetch(url, options);
    }
    

    Hope that helps!

    0 讨论(0)
提交回复
热议问题