簡體   English   中英

使用 gspread 寫入 Google 工作表時無法實現批量更新行

[英]Trouble implementing batch update rows while writing to a google sheet using gspread

我正在嘗試在使用 gspread 庫將數據寫入谷歌電子表格時批量更新行。 當以下 function get_content()產生單個結果時,我可以完美地batch update rows

import gspread
import requests
from oauth2client.service_account import ServiceAccountCredentials

link = 'https://api.coinmarketcap.com/data-api/v3/cryptocurrency/listing'
params = {
    'start': 1,
    'limit': '200',
    'sortBy': 'market_cap',
    'sortType': 'desc',
    'convert': 'USD,BTC,ETH',
    'cryptoType': 'all',
    'tagType': 'all',
    'audited': 'false',
    'aux': 'ath,atl,high24h,low24h,num_market_pairs,cmc_rank,date_added,max_supply,circulating_supply,total_supply,volume_7d,volume_30d,self_reported_circulating_supply,self_reported_market_cap'
}

def authenticate():
    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("creds.json", scope)
    client = gspread.authorize(creds)
    return client

def get_content(s,link,params):
    res = s.get(link,params=params)
    for item in res.json()['data']['cryptoCurrencyList']:
        yield item['id']

if __name__ == '__main__':
    with requests.Session() as s:
        s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
        client = authenticate()
        sheet = client.open("testFile").sheet1
        sheet.insert_row(['NAME'],1)
        item_list = []
        cell_list = sheet.range('A2:A201')
        for item in get_content(s,link,params):
            item_list.append(item)

        for i, val in enumerate(item_list):
            cell_list[i].value = val
        sheet.update_cells(cell_list)

但是,當相同的 function get_content()產生多個結果時,我找不到任何方法來batch update rows 這次的范圍是sheet.range('A2:D201')

def get_content(s,link,params):
    res = s.get(link,params=params)
    for item in res.json()['data']['cryptoCurrencyList']:
        yield item['id'],item['name'],item['symbol'],item['slug']

如何在使用 gspread 寫入谷歌表格時批量更新行?

在您的情況下,如何進行以下修改?

從:

item_list = []
cell_list = sheet.range('A2:A201')
for item in get_content(s,link,params):
    item_list.append(item)

for i, val in enumerate(item_list):
    cell_list[i].value = val
sheet.update_cells(cell_list)

至:

item_list = []
for item in get_content(s,link,params):
    item_list.append(item)

sheet.update('A2:D201', item_list, value_input_option='USER_ENTERED')

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM