从一个 Google Sheet 复制和粘贴到另一个

Copying and Pasting from one Google Sheet to another

我对 python 比较陌生,正在努力寻找一种使用 gspread 将数据从一个 google sheet 复制并粘贴到另一个的方法。有谁知道如何在不使用 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

从你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”列。请根据您的实际情况进行修改。

参考文献: