【发布时间】:2021-04-11 08:27:41
【问题描述】:
我在谷歌驱动器中有两个文件(两张谷歌表格),我需要以常规模式将数据和格式从一个文件移动到另一个文件。
如下图所示,我需要维护不同的文本格式(粗体、文本颜色等):
我的第一次尝试是: 使用 IMPORTRANGE 仅使用谷歌驱动表功能。它很好地复制了数据,但我丢失了我想在目标文件中保留的格式。
我的第二次尝试是: 使用 Python 和 gspread 包将数据和格式从源谷歌表复制到目标表。我有以下代码:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
source_file_sheet = 'https://docs.google.com/spreadsheets/X'
destination_file_sheet = 'https://docs.google.com/spreadsheets/Y'
service_key = "file.json"
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_file = ServiceAccountCredentials.from_json_keyfile_name(service_key, scope)
sourceSheetName = cod_source_system_file_operational
destinationSheetName = cod_source_system_file_billing
client = gspread.authorize(creds_file)
spreadsheet_source = client.open_by_url(source_file_sheet)
spreadsheet_destination = client.open_by_url(destination_file_sheet)
sourceSheetId = spreadsheet_source.worksheet('Sheet1')
destinationSheetId = spreadsheet_destination.worksheet('Sheet2')
body = {
"requests": [
{
"copyPaste": {
"source": {
"sheetId": sourceSheetId,
"startRowIndex": 3,
"endRowIndex": 10,
"startColumnIndex": 0,
"endColumnIndex": 5
},
"destination": {
"sheetId": destinationSheetId,
"startRowIndex": 0,
"endRowIndex": 10,
"startColumnIndex": 0,
"endColumnIndex": 5
},
"pasteType": "PASTE_NORMAL"
}
}
]
}
res = destinationSheetId.batch_update(body)
print(res)
但是当我运行它时,它给了我以下错误:
Traceback(最近一次调用最后一次):
dict(vr, range=absolute_range_name(self.title, vr['range']))
TypeError: string indices must be integers
我该如何解决我的问题?
感谢您的帮助!
【问题讨论】:
标签: python google-sheets request google-sheets-api gspread