【问题标题】:python gspread updating multiple cells from reponse bodypython gspread从响应体更新多个单元格
【发布时间】:2017-10-14 20:35:56
【问题描述】:

我正在使用这个 python 脚本从 Progresso API 获取响应: http://docs.progresso.apiary.io/#reference/behaviour/behaviour-events-collection/get-behaviour-events

from urllib2 import Request, urlopen
import smtplib import gspread 
from oauth2client.service_account import ServiceAccountCredentialseaders = {
'Authorization': 'Bearer [CURRENT_TOKEN]'
}
request = Request('https://private-anon-ae5edf57e7-progresso.apiary-
mock.com/BMEvents/?Behaviour=new', headers=headers)
response_body = urlopen(request).read()
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('ProgressoAPI-
2f6ecaa6635c.json', scope)
gc = gspread.authorize(credentials)
wks  = gc.open("Progresso Test").sheet1
wks.clear()
cell_list = wks.range('A1:H20')
for cell in cell_list:
cell.value = response_body
wks.update_cells(cell_list)

我知道 cell.value = 响应正文是错误的,我不知道如何才能正确 - 我被卡住了。

它出现在每个单元格中,如下所示: "{ ""BehaviourEntryId"": 13798177, ""LearnerId"": 245277, ""LearnerCode"": ""2009-0080"", ""RegGroup"": ""U6-RWE"", ""行为"": ""负面"", ""事件日期"": ""2017-02-07"", ""主题"": ""BE"", ""位置"": ""CLS"", ""已发布"": ""是"", ""创造者"": ""DhDr"", ""编辑器"": null, ""受让人"": ""DiRo"", ""状态"": ""已完成"", ““细节””: [ { ""类别"": ""CL"", ""类型"": ""CLatt"", ""严重性"": ""S2"", “点”:0 }, { ""类别"": ""CL"", ""类型"": ""CLBEH"", ""严重性"": ""S2"", “点”:2 } ], ““评论””: [ { ""BehaviourEntryCommentId"": 5648278, ""机密"":真实, ""评论"": ""被要求上厕所,去了最远的那个,只是为了浪费时间。"" }, { ""BehaviourEntryCommentId"": 5648279, ""机密"": false, ""评论"": ""把口香糖吐在地板上"" }, { ""BehaviourEntryCommentId"": 5648280, ""机密"": false, ""评论"": ""对员工很粗鲁"" } ], ""行动"": [ ""HTO"", ""ISO"" ] }"

如何在单元格范围内按照我想要的方式分隔文本并批量更新?

【问题讨论】:

    标签: python api gspread


    【解决方案1】:

    如果您的意思是两列,其中一行是“BehaviourEntryId”,另一行是 13798177,您可以尝试这样的操作:

    import json
    response = json.loads(response_body) #decode the json response string, returns a dict
    response_pairs = list(response.items)
    
    for i in range(1, len(response_body)+1):
        current_pair = response_pairs[i-1]
        current_key =  current_pair[0]
        current_value = current_pair[1]
        wks.update_acell('A{}'.format(i), current_key)
        wks.update_acell('B{}'.format(i), current_value)
    

    【讨论】:

    • 将其添加到代码中的最佳位置在哪里?我添加了这个,它一直给出无效的语法错误。
    • 在不了解整个代码的情况下我不太确定。语法错误在哪里?不过,导入应该始终放在代码的顶部。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多