2017年6月14日 星期三

Google Apps Script 入門到進階(13) --- Python、R、Excel 傳入數值到雲端 Google Sheet

今天來介紹如何用Python、R、Excel傳送數值到Google Sheet上,這幾僅提供Client端的傳送方法,Google Sheet端地接收程式,請讀者自行開發。
佈署Google網路應用程式:
Step 1. 佈署網路應用程式。

Step 2. 指定發布版本。

Step 3. 授權檔案。

Step 4. 允許存取。

Step 5. 取得網路應用程式URL。

以下為Client端,使用Python、R、Excel程式碼。
Python 2.7
import requests
def SendDataToGoogleSheet():
    url = "你的Google網路應用程式連結"
    payload = {'price':10049,
               'mkt':813,
               'bgac':470,
               'smac':191
              }
    resp=requests.get(url, params=payload)
    print resp.text

def main():
    SendDataToGoogleSheet()

if __name__ == '__main__':
    main()

R
library(httr)
url <- "你的Google網路應用程式連結"
postdata <- list("price"=10069,
                 "mkt"=611,
                 "bgac"=1876,
                 "smac"=333)
req <- GET(url, query = postdata, encode="from") 
status <- content(req , as ="text", encoding="utf-8")
status

Excel VBA
Sub SendMessage()
    Dim oXML As Object
    Dim URL As String, para As String    
    Dim price As Long, mkt As Long, bgac As Long, smac As Long

    price = 10069
    mkt = 611
    bgac = 1876
    smac = 333
    
    para = "price=" & price & "&mkt=" & mkt & "&bgac=" & bgac & "&smac=" & smac

    '傳送訊息網址
    URL = "你的Google網路應用程式連結?" & para

    '建立Ajax物件
    
    Set oXML = CreateObject("Msxml2.ServerXMLHTTP")
    With oXML
        '使用同步傳輸
        .Open "GET", URL, 0
        
        '執行Ajax傳送
        .send

        '顯示回報內容
        Debug.Print .responseText
    End With
    
    '釋放物件資源
    Set oXML = Nothing
End Sub

Excel VBA 操作影片

參考資料: