首页 > 解决方案 > 如何在每张纸上创建一个带有熊猫数据框的 google calc 文件

问题描述

我正在尝试使用 google sheet api 创建一个文件,该文件在每张表上都包含一个数据框。

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

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,但我不确定我做错了什么。

标签: pythonpandasgoogle-sheets

解决方案


  • 您想创建新的电子表格并放置数据框的值。
  • 您想通过 Python 使用 google-api-python-client 来实现此目的。
  • 您已经能够为电子表格放置和获取值。

如果我的理解是正确的,那么这个修改呢?我认为您的问题的原因是sheetofsheet = service.spreadsheets().create(body=sheet, fields='spreadsheetId').execute()不能用于sheetof set_with_dataframe(sheet, df)

我想提出2种模式。请将此视为几个答案之一。

模式一:

在此模式中,Sheets API 与 google-api-python-client 一起使用。新的电子表格是使用电子表格.create 的方法创建的,并且使用电子表格.值.更新的方法将值放入电子表格的第一个选项卡。

修改后的脚本:

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()

模式二:

在此模式中,使用 gspread 和 gspread_dataframe。如果使用gspread,脚本如下。关于credentials,请查看文档

示例脚本:

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)

笔记:

参考:

如果我误解了您的问题并且这不是您想要的结果,我深表歉意。


推荐阅读