【问题标题】:Copying and Pasting from one Google Sheet to another从一个 Google 表格复制和粘贴到另一个
【发布时间】:2021-11-30 19:28:07
【问题描述】:

我对 python 比较陌生,并且正在努力寻找一种使用 gspread 将数据从一个谷歌表复制和粘贴到另一个的方法。有谁知道如何在不使用win32复制到excel作为桥梁的情况下做到这一点?请参阅下面的代码和错误消息:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import numpy as np
Scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Documents\Scripts\FX Rates Query\key.json', Scope)

client = gspread.authorize(creds)

sheet = client.open("Capital").sheet1
data=sheet.get_all_records()

df = pd.DataFrame(data)
df.to_excel(r'C:\Users\Documents\Reserves_extract.xlsx')
sheet1 = client.open("Cash Duration ").sheet1
mgnt_fees = sheet1.col_values(5)
fees = pd.DataFrame(mgnt_fees)
fees1 = fees[fees!=0]
print(fees1)
update = sheet1.update('B7',fees1)
##^^ERROR MSG IS COMING FROM HERE

Error msg:

raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type DataFrame is not JSON serializable

【问题讨论】:

  • 我必须为我糟糕的英语水平道歉。不幸的是,从您的问题和脚本中,我无法理解您的目标。可以问一下copy and paste data from one google sheet to another的详细信息吗?您想将电子表格“A”中的所有值复制到电子表格“B”中。我的理解正确吗?
  • 嗨,我想将特定列从谷歌电子表格 A 复制到谷歌电子表格 B
  • 感谢您的回复。根据您的回复,我提出了一个修改后的脚本作为答案。你能确认一下吗?如果这没有用,我深表歉意。

标签: python google-sheets google-sheets-api gspread


【解决方案1】:

从您对I would like to copy a specific column from google spreadsheet A to google spreadsheet B的回复来看,在这种情况下,下面的修改如何?

修改脚本:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import numpy as np
Scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Documents\Scripts\FX Rates Query\key.json', Scope)

client = gspread.authorize(creds)

# I modified below script.
spreadsheetA = client.open("Capital")
spreadsheetB = client.open("Cash Duration ")
srcCol = "'" + spreadsheetA.sheet1.title + "'!A1:A" # This is the column "A" of the 1st tab of Spreadsheet A.
dstCol = "'" + spreadsheetB.sheet1.title + "'!B1:B" # This is the column "B" of the 1st tab of Spreadsheet B.
src = spreadsheetA.values_get(srcCol)
del src['range']
spreadsheetB.values_update(dstCol, params={'valueInputOption': 'USER_ENTERED'}, body=src)
  • 在此修改后的脚本中,将电子表格 A 的第一个选项卡的“A”列复制到电子表格 B 的第一个选项卡的“B”列。请根据您的实际情况进行修改。

参考资料:

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多