我们如何使用 Python 使用"Google Sheet API"用新数据更新工作表


  • https://developers.google.com/sheets/api/reference/rest
  • 我能够创建工作表,还可以清除工作表和其他一些操作
  • 但是我无法获得已经填充的"行数和列数",以便我可以在工作表中添加更多数据。
def nextAvailableRow(worksheet):
rowsUsed = len(filter(None, worksheet.col_values(1)))
return rowsUsed+1

此函数应将工作表作为参数,并输出下一个未使用的可用行。它接收第一列的所有值,然后筛选出所有空行以查找已使用的行数。

如果你只想在最后一行之后插入带有值的新数据,你可以使用spreadsheets.values.appendendpoint 来完成(请注意,你可以在"try this API"中使用 API,还有一个 Python 示例(

spreadsheet_id = 'your-spreadSheet-id'
ranges = "A1:A" # It will get the indo until the last row with data
value_render_option = "DIMENSION_UNSPECIFIED"
value_input_option = "USER_ENTERED"
# Body for the request 
value_range_body = {
"values": [
[
"A11",
"B11"
],
[
"A12",
"B12"
]
],
"majorDimension": "DIMENSION_UNSPECIFIED"
}
request = service.spreadsheets().values()
.append(spreadsheetId=spreadsheet_id, range=ranges, valueInputOption=value_input_option, body=value_range_body)
request.execute()

中的外部数组将表示行,内部数组表示列,如您在代码的示例正文中看到的那样。

注意:在另一个答案中,有人建议你使用第三个库,而不是Google Sheet的Python客户端库。我建议您使用官方谷歌库,因为它可以保证得到谷歌的支持。

最新更新