在Python中使用gdata.spreadsheets.client插入行
我在使用Python的gdata API处理谷歌表格时遇到了一些问题。通过gdata.spreadsheet.service,我可以很简单地创建一个字典,然后把它作为新的一行插入到谷歌表格中,像这样:http://www.mattcutts.com/blog/write-google-spreadsheet-from-python/。
Dict = {'weight':'600'}
spr_client.InsertRow(Dict, spreadsheet_key, worksheet_id)
现在我需要使用gdata.spreadsheets.client模块,因为我需要进行Oauth认证。我已经能够完成认证并编辑现有的单元格,但我还不能像之前那样根据某一列的值插入新的单元格或行。
这是我目前的进展:
import gdata.spreadsheets.client
import gdata.gauth
token = gdata.gauth.OAuth2Token(client_id='CLIENTID',
client_secret='CLIENTSECRET',
scope='https://spreadsheets.google.com/feeds/',
user_agent='blah.blah',
access_token='ACCESSTOKEN',
refresh_token='REFRESHTOKEN')
spr_client = gdata.spreadsheets.client.SpreadsheetsClient()
token.authorize(spr_client)
for entry in spr_client.get_list_feed('SPREADSHEETID', 'od6').entry:
print entry.to_dict()
entry.set_value('weight', '600')
spr_client.update(entry)
这段代码只是覆盖了“重量”列中的第一个值,而不是在下面的行中添加另一个值。如果能得到一些帮助,那就太好了。
4 个回答
你需要使用 CellQuery:
cell_query = gdata.spreadsheets.client.CellQuery( min_row=1, max_row=1, min_col=1, max_col=1, return_empty=True) cells = gd_client.GetCells(sprd_key, wrksht_key, q=cell_query) cell_entry = cells.entry[0] cell_entry.cell.input_value = 'Address' gd_client.update(cell_entry) # This is the call to Google Server to update
要进行批量更新,可以使用:
range = "A6:D1113" cellq = gdata.spreadsheets.client.CellQuery(range=range, return_empty='true') cells = gd_client.GetCells(sprd_key, wrksht_key, q=cellq) batch = gdata.spreadsheets.data.BuildBatchCellsUpdate(sprd_key, wrksht_key) n = 1 for cell in cells.entry: cell.cell.input_value = str(n) batch.add_batch_entry(cell, cell.id.text, batch_id_string=cell.title.text, operation_string='update') n = n + 1 gd_client.batch(batch, force=True) # A single call to Google Server to update all cells.
希望这对你有帮助。
spr_client.InsertRow 这个方法不能用,因为 gdata.spreadsheets.client.SpreadsheetsClient 这个类里没有 InsertRow 方法,下面是相关的内容:
(Pdb) p sheets_service
<gdata.spreadsheets.client.SpreadsheetsClient object at 0x7fa3b0bd0390>
(Pdb) p dir(sheets_service)
['AddListEntry', 'AddRecord', 'AddTable', 'AddWorksheet', 'Batch', 'ClientLogin', 'Delete', 'Get', 'GetAccessToken', 'GetCell', 'GetCells', 'GetEntry', 'GetFeed', 'GetListFeed', 'GetNext', 'GetOAuthToken', 'GetRecord', 'GetRecords', 'GetSpreadsheets', 'GetTables', 'GetWorksheet', 'GetWorksheets', 'ModifyRequest', 'Post', 'Put', 'Request', 'RequestClientLoginToken', 'RevokeToken', 'Update', 'UpgradeToken', '_GDClient__gsessionid', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add_list_entry', 'add_record', 'add_table', 'add_worksheet', 'alt_auth_service', 'api_version', 'auth_scopes', 'auth_service', 'auth_token', 'batch', 'client_login', 'delete', 'get', 'get_access_token', 'get_cell', 'get_cells', 'get_entry', 'get_feed', 'get_list_feed', 'get_next', 'get_oauth_token', 'get_record', 'get_records', 'get_spreadsheets', 'get_tables', 'get_worksheet', 'get_worksheets', 'host', 'http_client', 'modify_request', 'post', 'put', 'request', 'request_client_login_token', 'revoke_token', 'source', 'ssl', 'update', 'upgrade_token', 'xoauth_requestor_id']
它有的功能是 AddRecord,这个功能是最接近我们想要的。不过,AddRecord 需要一个表格的 ID,而我还没弄明白这个 ID 怎么获取。看到的所有例子似乎都是在用 gdata.spreadsheet.service.SpreadsheetsService,这个类里是有 InsertRow 方法的。
我觉得你想要的是:
spr_client.InsertRow(entry.to_dict(), 'SPREADSHEETID', 'od6')
我又看了一下,现在谷歌终于把 gdata.spreadsheet.service.SpreadsheetsService() 中的 ProgrammaticLogin() 删掉了(也就是不再支持用用户名和密码登录)。使用 OAuth2 和更新版本的 gdata python API,解决方法相对简单。
import gdata.spreadsheets.client
import gdata.spreadsheets.data
import gdata.gauth
# create the OAuth2 token
token = gdata.gauth.OAuth2Token(client_id='CLIENTID',
client_secret='CLIENTSECRET',
scope='https://spreadsheets.google.com/feeds/',
user_agent='blah.blah',
access_token='ACCESSTOKEN',
refresh_token='REFRESHTOKEN')
# create the spreadsheet client and authenticate
spr_client = gdata.spreadsheets.client.SpreadsheetsClient()
token.authorize(spr_client)
#create a ListEntry. the first item of the list corresponds to the first 'header' row
entry = gdata.spreadsheets.data.ListEntry()
entry.set_value('ham', 'gary')
entry.set_value('crab', 'sack')
# add the ListEntry you just made
spr_client.add_list_entry(entry, 'SPREADSHEETID', 'od6')
这段代码会在最后一行数据后面添加一行新数据。要小心空行,因为 'ListFeed' 只会计算到最后一行有数据的行。另外,还有更优雅的方法来获取电子表格的密钥和工作表的 ID,不过电子表格的密钥可以在你想编辑的表格的 URL 中找到,而第一个工作表通常是 od6。如果不是 od6,这个链接可以帮你找到: https://spreadsheets.google.com/feeds/worksheets/YOUR_SPREADSHEET_ID/private/full