查看如何获取工作表最新行的数据的技巧。我已经看到了获取所有数据然后获取其长度的解决方案。
但这当然是浪费所有的获取。想知道是否有一种聪明的方法可以做到这一点,因为您已经可以使用
worksheet.append_rows([some_data])
将数据附加到最后一行+1
我在另一个问题中找到了这段代码,它在工作表中创建了一个虚拟附加。
之后,您可以稍后搜索位置:
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
您可以在此文档中查看 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)
我使用了解决方案@buran metnion。如果您使用
初始化工作表add_worksheet(title="title", rows=1, cols=10)
并且仅通过
追加新数据worksheet.append_rows([some_array])
那么 @buran 的建议非常适合简单使用
worksheet.row_count
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=spreadsheet_id, range=f"{sheet_name}!A:A").execute()
values = result.get('values', [])
last_row = len(values) + 1