【发布时间】:2018-08-27 22:59:29
【问题描述】:
我只想应用来自 JSON 条目的格式。我做的第一件事是在我的电子表格上为所有列的第二行制作我想要的格式。然后我通过 .get 请求(从 A2 到 AO3)检索了它们。
request = google_api.service.spreadsheets().get(
spreadsheetId=ss_id,
ranges="Tab1!A2:AO3",
includeGridData=True).execute()
接下来我做的是收集每列的每种格式并将它们记录在字典中。
my_dictionary_of_formats = {}
row_values = row_1['sheets'][0]['data'][0]['rowData'][0]['values']
for column in range(0, len(row_values)):
my_dictionary_of_formats[column] = row_values[column]['effectiveFormat']
现在我有一个包含所有列的所有有效格式的字典。我现在无法将该格式应用于每列中的所有行。我尝试了batchUpdate 请求:
cell_data = {
"effectiveFormat": my_dictionary_of_formats[0]}
row_data = {
"values": [
cell_data
]
}
update_cell = {
"rows": [
row_data
],
"fields": "*",
"range":
{
"sheetId": input_master.tab_id,
"startRowIndex": 2,
"startColumnIndex": 0,
"endColumnsIndex": 1
}
}
request_body = {
"requests": [
{"updateCells": update_cell}],
"includeSpreadsheetInResponse": True,
"responseIncludeGridData": True}
service.spreadsheets().batchUpdate(spreadsheetId=my_id, body=request_body).execute()
这消灭了一切,我不知道为什么。我不认为我理解 fields='* 属性。
TL;DR 我想将格式应用于单个列中的所有行。就像我在第二行第一列上使用“Paint Format”工具并将其一直拖到最后一行一样。
-----更新
您好,感谢 cmets,这是我的解决方案:
###collect all formats from second row
import json
row_2 = goolge_api.service.spreadsheets().get(
spreadsheetId=spreadsheet_id,
ranges="tab1!A2:AO2",
includeGridData=True).execute()
my_dictionary = {}
row_values = row_2['sheets'][0]['data'][0]['rowData'][0]['values']
for column in range(0,len(row_values)):
my_dictionary[column] = row_values[column]
json.dumps(my_dictionary,open('config/format.json','w'))
###Part 2, apply formats
requests = []
my_dict = json.load(open('config/format.json'))
for column in my_dict:
requests.append(
{
"repeatCell": {
"range": {
"sheetId": tab_id,
"startRowIndex": str(1),
"startColumnIndex":str(column),
"endColumnIndex":str(int(column)+1)
},
"cell": {
"userEnteredFormat": my_dict[column]
},
'fields': "userEnteredFormat({})".format(",".join(my_dict[column].keys()))
}
})
body = {"requests": requests}
google_api.service.spreadsheets().batchUpdate(spreadsheetId=s.spreadsheet_id,body=body).execute()
【问题讨论】:
-
我不知道我可以回答我自己的问题...
-
你为什么不能呢?您只是不允许在发布后的一定时间内接受您自己的答案作为解决方案 - 在该窗口之后,您绝对可以并且应该确保将最佳答案标记为已接受的答案。该窗口是为了让其他人也有机会提供答案stackoverflow.com/help/self-answer
标签: python google-sheets-api google-api-python-client