【问题标题】:Python gspread - get the last row without fetching all the data?Python gspread - 在不获取所有数据的情况下获取最后一行?
【发布时间】:2022-08-06 03:44:25
【问题描述】:

查看提示如何获取工作表最新行的数据。我已经看到了获取所有数据然后取其长度的解决方案。

但这当然是对所有这些获取的浪费。想知道是否有一种聪明的方法可以做到这一点,因为您已经可以使用worksheet.append_rows([some_data]) 将数据附加到最后一行+1

  • 我记得使用 AppScript 创建一个隐藏选项卡,该选项卡每隔几分钟运行一次以计算最大索引(列和行),然后我可以查询它以追加/获取数据。
  • 也许您可以使用worksheet.row_count 然后worksheet.row_values() 用于该行?

标签: python google-sheets gspread


【解决方案1】:

我使用了@buran metnion 的解决方案。如果你用

add_worksheet(title="title", rows=1, cols=10)

并且仅通过添加新数据

worksheet.append_rows([some_array])

然后@buran 的建议非常适合简单地使用

worksheet.row_count

【讨论】:

    【解决方案2】:

    我在另一个问题中找到了此代码,它在工作表中创建了一个虚拟附加。

    之后,您可以稍后搜索该位置:

    def get_last_row_with_data(service, value_input_option="USER_ENTERED"):
        last_row_with_data = '1'
        try:
            # creates a dummy row
    
            dummy_request_append = service.spreadsheets().values().append(
                spreadsheetId='<spreadsheet id>',
                range="{0}!A:{1}".format('Tab Name', 'ZZZ'),
                valueInputOption='USER_ENTERED',
                includeValuesInResponse=True,
                responseValueRenderOption='UNFORMATTED_VALUE',
                body={
                    "values": [['']]
                }
            ).execute()
    
            # Search the dummy row
    
            a1_range = dummy_request_append.get('updates', {}).get('updatedRange', 'dummy_tab!a1')
            bottom_right_range = a1_range.split('!')[1]
            number_chars = [i for i in list(bottom_right_range) if i.isdigit()]
            last_row_with_data = ''.join(number_chars)
    
        except Exception as e:
            last_row_with_data = '1'
    
        return last_row_with_data
    

    您可以在 documentation 中看到 Append 的示例。

    但是,对我来说,它更容易使用:

    # The ID of the sheet you are working with. 
    
    Google_sheets_ID = 'ID_of_your_Google_Sheet' 
    
    # define the start row that has data
    # it will later be replace with the last row
    # in my test sheet, it starts in row 2
    
    last_row = 2 
    
    # code to the get the last row
    # range will be the column where the information is located
    # remember to change "sheet1" for the name of your worksheet. 
    
    response = service.spreadsheets().values().get(
        spreadsheetId = Google_sheets_ID,
        range = 'sheet1!A1:A'
    )execute()
    
    #Add the initial value where the range started to the last row with values 
    Last_row += len(response['values']) - 1 
    
    #If you print last row, you should see the last row with values in the Sheet. 
    print(last_row) 
    

    【讨论】:

    • 谢谢你 2 条可能对其他人有用的好建议。正如我在另一个答案中所写的那样,我以另一种方式发泄
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2020-11-08
    • 2011-02-03
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多