【发布时间】:2019-08-03 16:14:34
【问题描述】:
我一直在尝试写入谷歌表格,我已经能够这样做,但是我不想修改和添加越来越多的数据,我希望数据被覆盖(在同一位置删除和替换)我'正在使用 python,虽然它并不重要......一个 R-PI。
# import many libraries
# -*- coding: utf-8 -*-
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from oauth2client.service_account import ServiceAccountCredentials
#import bme280
import datetime
# My Spreadsheet ID ... See google documentation on how to derive this
MY_SPREADSHEET_ID = '...............someID.....................'
def update_sheet(sheetname, my_list):
"""update_sheet method:
appends a row of a sheet in the spreadsheet with the
the latest temperature, pressure and humidity sensor data
"""
# authentication, authorization step
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
creds = ServiceAccountCredentials.from_json_keyfile_name(
'client_secret.json', SCOPES)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API, append the next row of sensor data
# values is the array of rows we are updating, its a single row
values = [ [ str(datetime.datetime.now()), my_list ] ]
body={'values': my_list}
result = service.spreadsheets().values().append(
spreadsheetId=MY_SPREADSHEET_ID,
range = 'PCEM SHT.1' +'!A2:A7',
valueInputOption = 'RAW',
body=body).execute()
def main():
my_list = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
update_sheet("PCEM SHT.1", my_list)
if __name__ == '__main__':
main()
【问题讨论】:
-
您正在使用
append()将值附加到电子表格中。请改用update()。 -
成功了,谢谢!此外,我必须将范围从 range = 'PCEM SHT.1' +'!A2:A7' 更改为 range = 'PCEM SHT.1' +'!A2:B2'
标签: python google-sheets-api overwrite