【问题标题】:Issues / question with batch update with pygsheets / google sheets使用 pygsheets / google 表格进行批量更新的问题/问题
【发布时间】:2021-02-05 18:36:01
【问题描述】:

好吧,我是 python 新手,但是……我真的很喜欢它。我一直在努力解决这个问题,并认为有人可以提供比我了解更多的人。

所以我想做的是使用 pygsheets 并将批量更新与一个 api 调用与多个结合起来。我一直在寻找示例或想法,发现如果您取消链接并链接它会这样做吗?我试过了,它只加快了一点速度,然后我看了看,你可以使用 update.values 与 update.value。我已经让它与这样的东西一起工作 wk1.update_values('A2:C4',[[1,2,3],[4,5,6],[7,8,9]]) 但如果您希望更新位于特定单元格位置而不是 a2:c4 之类的范围?感谢您提前提供任何建议。

https://pygsheets.readthedocs.io/en/latest/worksheet.html#pygsheets.Worksheet.update_values https://pygsheets.readthedocs.io/en/latest/sheet_api.html?highlight=batch_updates#pygsheets.sheet.SheetAPIWrapper.values_batch_update

import pygsheets

gc = pygsheets.authorize() # This will create a link to authorize 

#  Open spreadsheet  

GS_ID = ''
File_Tab_Name = 'File1'
Main_Topic = 'Main Topic'
Actual_Company_Name = 'Company Name'
Street = 'Street Address'
City_State_Zip = 'City State Zip'
Phone_Number = 'Phone Number'


# 2. Open spreadsheet by key
sh = gc.open_by_key(GS_ID)

sh.title = File_Tab_Name
wk1 = sh[0]
wk1.title = File_Tab_Name
#wk1.update_values('A2:C4',[[1,2,3],[4,5,6],[7,8,9]])  
wk1.update_values([['a1'],['h1'],['i3']],[[Main_Topic],[Actual_Company_Name],[Street]])   ### is this possible
#wk1.unlink()
#wk1.title = File_Tab_Name
#wk1.update_value("a1",Main_Topic)  ###Topic
#wk1.update_value("h1",Actual_Company_Name)  ###Company Name
#wk1.update_value("i3",Street)  ###Street Address
#wk1.update_value("i4",City_State_Zip)  ###City State Zip
#wk1.update_value("i5",Phone_Number)   ### Phone Number
#wk1.link() # will do all the updates

【问题讨论】:

    标签: python python-3.x google-sheets pygsheets


    【解决方案1】:

    据我所知,您希望批量更新值。你可以使用update_values_batch函数。

    wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1],[2]], [[3],[4]]])
    # or
    wks.update_values_batch([((1,1), (2,1)), 'B1:B2'], [[[1,2]], [[3,4]]], 'COLUMNS')
    # or
    wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1,2]], [[3,4]]], 'COLUMNS')
    

    doc here

    注意:将 pygsheets 更新到最新版本或从 gitub 安装

    pip install --upgrade https://github.com/nithinmurali/pygsheets/archive/staging.zip
    

    【讨论】:

    • 没问题。如果答案解决了您的问题,请将其标记为已接受未来用户。
    【解决方案2】:

    很遗憾,pygsheets 无法批量更新多个范围。相反,您可以使用 gspread

    gspread 具有 batch_update 方法,您可以在其中一次更新多个单元格或范围。

    示例:

    代码:

    import gspread
    
    gc = gspread.service_account()
    sh = gc.open_by_key("insert spreadsheet key here").sheet1
    sh.batch_update([{
        'range': 'A1:B1',
        'values': [['42', '43']],
    }, {
        'range': 'A2:B2',
        'values': [['44', '45']],
    }])
    

    输出:

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      相关资源
      最近更新 更多