Jump to content

Python interagindo com Google Sheets


RamiroJunior1

Postagens Recomendadas

Pessoal, poderiam validar meu código e verificar o que estou fazendo de errado.

Minha intenção é: Apagar os dados a partir da Coluna/Linha A2 no Google Sheets e colar os dados apartir da Coluna/Linha A2 da planilha direcionada pelo Pandas.

Creio que esteja faltando a parte de excluir os dados onde coloquei em vermelho, não estou sabendo qual. Eu coloquei pra rodar com poucos dados e deu certo desse jeito. Com muita informação, em média de 100~2000 linhas ele da os erros lá no final.

 

from __future__ import print_function
import pandas as pd
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build


tabela = pd.read_excel('DIRETORIO DA PLANILHA QUE VOU COPIAR DADOS')

print(tabela.values.tolist())

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']


def main():
    creds = None

    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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(
                'client_secret.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('sheets', 'v4', credentials=creds)

 # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId='LINK PLANILHA GOOGLE QUE QUERO INSERIR DADOS',
                                range='Base!A2:R9999').execute()
    values = result.get('values', [])
    print(values)

    service.spreadsheets().values().update(spreadsheetId='LINK PLANILHA GOOGLE QUE QUERO INSERIR DADOS',
                                           range='Base!A2',
                                           body={'majorDimension': 'ROWS', 'values': tabela.values.tolist()}
                                           ).execute()


if __name__ == '__main__':
    main()

 

----------------------------------------------------------------------- ERROS ---------------------------------------------------------------------------------------------

 

Traceback (most recent call last):
  File "C:\Users\87839\pythonProject1\Sheets.py", line 52, in <module>
    main()
  File "C:\Users\87839\pythonProject1\Sheets.py", line 45, in main
    service.spreadsheets().values().update(spreadsheetId='10SQLGYQOM8qShtjPlcFzlFsjZ1gNfcA9EnRj33p-oUM',
  File "C:\Users\87839\AppData\Roaming\Python\Python310\site-packages\googleapiclient\discovery.py", line 1094, in method
    headers, params, query, body = model.request(
  File "C:\Users\87839\AppData\Roaming\Python\Python310\site-packages\googleapiclient\model.py", line 160, in request
    body_value = self.serialize(body_value)
  File "C:\Users\87839\AppData\Roaming\Python\Python310\site-packages\googleapiclient\model.py", line 273, in serialize
    return json.dumps(body_value)
  File "C:\Users\87839\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 235, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\87839\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\87839\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\87839\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

Process finished with exit code 1

Link to comment
Compartilhe em outros sites

2 horas atrás, geovaniif disse:

oi!

 

tenta converter a coluna de data do seu dataframe, para ser uma string. Eu tive um problema assim, e, se não me falha a memória, era problema com data.

Desculpe-me por ser meio leigo, estou aprendendo python tem apenas alguns dias.
Consegue explicar como faze-lo ? 

Link to comment
Compartilhe em outros sites

1 hora atrás, RamiroJunior1 disse:

Desculpe-me por ser meio leigo, estou aprendendo python tem apenas alguns dias.
Consegue explicar como faze-lo ? 

claro!

vamos supor que o seu dataframe chama-se "df" e que a coluna que é uma data chama-se 'minha_data'

df['minha_data'] = (df['minha_data']).astype(str)

 

Link to comment
Compartilhe em outros sites

Crie uma conta ou entre para comentar 😀

Você precisa ser um membro para deixar um comentário.

Crie a sua conta

Participe da nossa comunidade, crie sua conta.
É bem rápido!

Criar minha conta agora

Entrar

Você já tem uma conta?
Faça o login agora.

Entrar agora


×
×
  • Create New...