Ir para conteúdo
Fórum Script Brasil
  • 0

Python interagindo com Google Sheets


Ramiro Junior

Pergunta

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
 

 

 

 

 

Editado por Ramiro Junior
Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...