从一个Google表格复制和粘贴到另一个表格

3

我对Python比较新,正在努力找到一种使用gspread将数据从一个Google表格复制到另一个Google表格的方法。有没有人知道如何在不使用win32作为桥梁的情况下完成这个操作?请看下面的代码和错误信息:

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

我必须为我的英语水平道歉。不幸的是,从你的问题和脚本中,我无法理解你的目标。我可以问一下关于“从一个谷歌表格复制和粘贴数据到另一个表格”的详细信息吗?你想要将电子表格“A”的一个工作表中的所有值复制到电子表格“B”的一个工作表中。我的理解正确吗? - Tanaike
嗨,我想从Google电子表格A复制特定列到Google电子表格B。 - user16274307
谢谢您的回复。根据您的回复,我提出了一个修改后的脚本作为答案。请问您能否确认一下?如果这个脚本对您没有用,我很抱歉。 - Tanaike
1个回答

2

根据您的回复:我想将 Google 电子表格 A 中的特定列复制到 Google 电子表格 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"。请根据实际情况进行修改。
参考资料:
- values_get - values_update

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接