Se avete letto ed eseguito il primo tutorial su come leggere un foglio elettronico di google drive in Pyton per scrivere bastano poche modifiche.
1)
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
modificare con:
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
Permette di chiedere l’autorizzazione a tutte le attività su foglio di Google.
2)
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
Inserire il codice del foglio da modificare.
Ogni foglio oltre al nome ha un codice verificabile nelle Proprietà.
3)
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[1]))
Sostituire con:
values = [[200,201],[800,801],[700,701]]
body = {
'values': values
}
result = service.spreadsheets().values().update(
spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME,
valueInputOption='RAW', body=body).execute()
print('{0} cells updated.'.format(result.get('updatedCells')))
I valori descritti in values sono quelli che verranno scritti.
—————Codice completo———————
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '12A0A8ntEwWRkjdVFylZi7IJF3VbSjnlkQtGokjNWmEg'
SAMPLE_RANGE_NAME = 'prove!A1:B'
ValueInputOption = 'RAW'
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
values = [
[200,201],
[800,801],
[700,701]
]
body = {
'values': values
}
result = service.spreadsheets().values().update(
spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME,
valueInputOption='RAW', body=body).execute()
print('{0} cells updated.'.format(result.get('updatedCells')))
if __name__ == '__main__':
main()
NOTE:
Per scrivere il codice del foglio indicato deve essere quello di un proprio foglio
il foglio deve essere indicato come condivisibile
Se si è già compilato l’esempio precedente o si cambia l’indirizzo del foglio bisogna cancellare il file token.pikle che viene generato quando si autorizza l’utente ad accedere e che si trova nella directory del sorgente.
Solo a titolo esemplificativo ecco l’output di un sorgente che gira su un Raspberry con sensore di temperatura ed umidità e che aggiorna una pagina web ogni 15 minuti. Link