2017-10-08 10 views
0

pythonとGoogle APIを使用してGoogleスプレッドシートへの書き込みに問題があります。コードは次のとおりです。Python Google APIによるGoogleシートへの書き込み

import httplib2 
import os 

from apiclient import discovery 
from oauth2client import client 
from oauth2client import tools 
from oauth2client.file import Storage 

try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
except ImportError: 
    flags = None 

# If modifying these scopes, delete your previously saved credentials 
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json 
SCOPES = 'https://www.googleapis.com/auth/spreadsheets' 
#this scope allows reading and writing to the sheet 
CLIENT_SECRET_FILE = 'client_secret.json' 
APPLICATION_NAME = 'Google Sheets API Python Quickstart' 


def get_credentials(): 
"""Gets valid user credentials from storage. 

If nothing has been stored, or if the stored credentials are invalid, 
the OAuth2 flow is completed to obtain the new credentials. 

Returns: 
    Credentials, the obtained credential. 
""" 
    home_dir = os.path.expanduser('~') 
    credential_dir = os.path.join(home_dir, '.credentials') 
    if not os.path.exists(credential_dir): 
     os.makedirs(credential_dir) 
    credential_path = os.path.join(credential_dir, 
     'sheets.googleapis.com-python-quickstart.json') 

    store = Storage(credential_path) 
    credentials = store.get() 
    if not credentials or credentials.invalid: 
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
     flow.user_agent = APPLICATION_NAME 
     if flags: 
      credentials = tools.run_flow(flow, store, flags) 
     else: # Needed only for compatibility with Python 2.6 
      credentials = tools.run(flow, store) 
     print('Storing credentials to ' + credential_path) 
    return credentials 

def main(): 
"""Shows basic usage of the Sheets API. 

Creates a Sheets API service object and prints the names and majors of 
students in a sample spreadsheet: 

https://docs.google.com/spreadsheets/d/\ 
    1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY 
""" 
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?' 
       'version=v4') 
    service = discovery.build('sheets', 'v4', http=http, 
          discoveryServiceUrl=discoveryUrl) 

    spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY' 
    #see also https://developers.google.com/sheets/api/guides/values 
    #https://developers.google.com/sheets/api/samples/writing 
    PUT https://sheets.googleapis.com/v4/spreadsheets/\ 
    spreadsheets/d/spreadsheetId/values/\ 
    sheet1!A1:D5?valueInputOption=USER_ENTERED 
     values = { 
     "range": "'Main'!A1:D5", 
     "majorDimension": "ROWS", 
     "values": [ 
     ["Item", "Cost", "Stocked", "Ship Date"], 
     ["Wheel", "$20.50", "4", "3/1/2016"], #new row 
     ["Door", "$15", "2", "3/15/2016"], 
     ["Engine", "$100", "1", "30/20/2016"], 
     ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"] 
     ], 
    } 
    result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheet_id, range=range_name, 
    valueInputOption=value_input_option, body=body).execute() 


if __name__ == '__main__': 
    main() 

私は自分のシートからデータを取得するquickstart.pyを持っています。 https://developers.google.com/drive/v3/web/quickstart/python

シートが透明です。

エラーメッセージは次のとおりです。次のスクリプトにmain()の変更について

PUT https://sheets.googleapis.com/v4/spreadsheets/spreadsheets/\ 
d/spreadsheetId/values/sheet1!A1:D5?valueInputOption=USER_ENTERED 
      ^

SyntaxError: invalid syntax 
+0

最後の質問でドキュメントをリンクしました。今はテストできませんが、Pythonでは 'PUT'はありません。あなたのコードの残りの部分は、あなたが適切な言語のグリップを持っていることを示唆しているので、私はここで混乱を理解していません。 – roganjosh

+0

私の答えは機能しましたか?あなたはそれについて教えてくれませんか?それは私が勉強するのにも役立ちます。これがうまくいけば、あなたと同じ問題を抱えている他の人もあなたの質問を解決できる質問にすることができます。 – Tanaike

答えて

0

どのように?

spreadsheets.values.updateの詳細情報はhereです。

def main(): 
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?' 
        'version=v4') 
    service = discovery.build('sheets', 'v4', http=http, 
           discoveryServiceUrl=discoveryUrl) 

    spreadsheet_id = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY' 
    range_name = 'Main!A1:D5' 
    body = { 
     "majorDimension": "ROWS", 
     "values": [ 
      ["Item", "Cost", "Stocked", "Ship Date"], 
      ["Wheel", "$20.50", "4", "3/1/2016"], # new row 
      ["Door", "$15", "2", "3/15/2016"], 
      ["Engine", "$100", "1", "30/20/2016"], 
      ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"] 
     ], 
    } 
    result = service.spreadsheets().values().update(
     spreadsheetId=spreadsheet_id, 
     range=range_name, 
     body=body, 
     valueInputOption='USER_ENTERED' 
    ).execute() 
    print(result) 
関連する問題