如何创建一个google计算文件,每个sh上都有一个数据帧

2024-09-28 20:57:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用googlesheetapi创建一个文件,在每个表上包含一个数据帧。你知道吗

代码失败了,我不知道如何修复它。你知道吗

import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from gspread_dataframe import get_as_dataframe, set_with_dataframe


    title = 'example_api'
    SCOPES = ['https://www.googleapis.com/auth/drive.file']

    flow = InstalledAppFlow.from_client_secrets_file(
        '/home/lpuggini/MyApps/credentials.json', SCOPES)
    creds = flow.run_local_server(port=0)


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


    sheet = {
        'properties': {
            'title': title
        }
    }
    sheet = service.spreadsheets().create(body=sheet,
                                          fields='spreadsheetId').execute()
    print('Spreadsheet ID: {0}'.format(sheet.get('spreadsheetId')))

    df = pd.DataFrame.from_records([{'a': i, 'b': i * 2} for i in range(100)])
    set_with_dataframe(sheet, df)

我得到以下错误:

lpuggini@lpuggini-T3420:~/Desktop$ python prova.py 
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=541601611663-74g6a9ue9e8a6ps212cfu3q6lpens1hv.apps.googleusercontent.com&redirec
t_uri=http%3A%2F%2Flocalhost%3A38071%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file&state=vhowmlA2HbiOdnLjegDwjcZphneA4F&access_type=offline&code_challenge=EiewMpshQe8K-4qJmtTMyhHynmIs-wIV5
YC3BFVjXJs&code_challenge_method=S256
[27080:27099:0807/162558.128868:ERROR:browser_process_sub_thread.cc(203)] Waited 3 ms for network service
Opening in existing browser session.
Spreadsheet ID: 1qAuJf0KMl3Gsgbzu4nBBEIrd9kO0byMlCCZhndHWrOo
Traceback (most recent call last):
  File "prova.py", line 29, in <module>
    set_with_dataframe(sheet, df)
  File "/home/lpuggini/VirtualEnvs/diagnosis_analysis_venv/lib/python3.6/site-packages/gspread_dataframe.py", line 176, in set_with_dataframe
    _resize_to_minimum(worksheet, y, x)
  File "/home/lpuggini/VirtualEnvs/diagnosis_analysis_venv/lib/python3.6/site-packages/gspread_dataframe.py", line 68, in _resize_to_minimum
    worksheet.col_count,
AttributeError: 'dict' object has no attribute 'col_count'
lpuggini@lpuggini-T3420:~/Desktop$ 

我认为我没有正确使用api,但我不确定我做错了什么。你知道吗


Tags: infrompyimportcomauthdataframetitle
1条回答
网友
1楼 · 发布于 2024-09-28 20:57:23
  • 您需要创建新的电子表格并将dataframe的值放入。你知道吗
  • 您希望通过使用带有python的googleapi python客户端来实现这一点。你知道吗
  • 您已经能够为电子表格输入和获取值。你知道吗

如果我的理解是正确的,这个修改怎么样?我认为你的问题的原因是sheetsheet = service.spreadsheets().create(body=sheet, fields='spreadsheetId').execute()不能用于sheetset_with_dataframe(sheet, df)。你知道吗

我想提出两种模式。请把这看作几个答案之一。你知道吗

模式1:

在这种模式中,sheetsapi与googleapi python客户端一起使用。新的电子表格是使用电子表格.创建,并使用电子表格.值.更新. 你知道吗

修改脚本:

import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from gspread_dataframe import get_as_dataframe, set_with_dataframe

title = 'example_api'
SCOPES = ['https://www.googleapis.com/auth/drive.file']

flow = InstalledAppFlow.from_client_secrets_file(
    '/home/lpuggini/MyApps/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
service = build('sheets', 'v4', credentials=creds)

# Create new Spreadsheet.
sheet = {
    'properties': {
        'title': title
    }
}
sheet = service.spreadsheets().create(
    body=sheet, fields='spreadsheetId').execute()

df = pd.DataFrame.from_records([{'a': i, 'b': i * 2} for i in range(100)])
value_range_body = {
    'values': df.values.tolist()
}

# Put values to the created Spreadsheet.
res = service.spreadsheets().values().update(
    spreadsheetId=sheet['spreadsheetId'], range="A1", valueInputOption="USER_ENTERED", body=value_range_body).execute()
print(res)
  • 如果creds = flow.run_local_server(port=0)发生错误,请修改为creds = flow.run_local_server()。你知道吗

模式2:

在这个模式中,使用了gspread和gspread\u数据帧。如果使用gspread,脚本如下所示。关于credentials,请检查the document。你知道吗

示例脚本:

client = gspread.authorize(credentials)

# Create new Spreadsheet.
sh = client.create('sample title')
sheet = sh.sheet1

df = pd.DataFrame.from_records([{'a': i, 'b': i * 2} for i in range(100)])

# Put values to the created Spreadsheet.
set_with_dataframe(sheet, df)

注:

参考文献:

如果我误解了你的问题,而这不是你想要的结果,我道歉。你知道吗

相关问题 更多 >