在添加数据之前使用Python gdata清除工作表中的行

时间:2012-08-07 16:28:16

标签: python gdata-api

我有一个Google电子表格,我使用python脚本和gdata库填充值。如果我不止一次运行脚本,它会在工作表中添加新行,我希望脚本在填充之前首先清除行中的所有数据,这样每次运行时都会有一组新的数据脚本。我尝试过使用:

UpdateCell(row, col, value, spreadsheet_key, worksheet_id)

但是没有像这样运行两个for循环,是否有更简洁的方法?这个循环似乎也非常缓慢:

for x in range(2, 45):
      for i in range(1, 5):
        self.GetGDataClient().UpdateCell(x, i, '', 
                                         self.spreadsheet_key,
                                         self.worksheet_id)

1 个答案:

答案 0 :(得分:11)

不确定您是否已将其整理出来,但关于加快清除当前数据的速度,请尝试使用batch request。例如,要清除工作表中的每个单元格,您可以执行以下操作:

cells = client.GetCellsFeed(key, wks_id)
batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed()

# Iterate through every cell in the CellsFeed, replacing each one with ''
# Note that this does not make any calls yet - it all happens locally
for i, entry in enumerate(cells.entry):
  entry.cell.inputValue = ''
  batch_request.AddUpdate(cells.entry[i])

# Now send the entire batchRequest as a single HTTP request
updated = client.ExecuteBatch(batch_request, cells.GetBatchLink().href)

如果你想要保存列标题(假设它们在第一行),你可以使用CellQuery:

# Set up a query that starts at row 2
query = gdata.spreadsheet.service.CellQuery()
query.min_row = '2'

# Pull just those cells
no_headers = client.GetCellsFeed(key, wks_id, query=query)

batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed()

# Iterate through every cell in the CellsFeed, replacing each one with ''
# Note that this does not make any calls yet - it all happens locally
for i, entry in enumerate(no_headers.entry):
  entry.cell.inputValue = ''
  batch_request.AddUpdate(no_headers.entry[i])

# Now send the entire batchRequest as a single HTTP request
updated = client.ExecuteBatch(batch_request, no_headers.GetBatchLink().href)

或者,您也可以使用它来更新您的单元格(可能更符合您的要求)。文档的链接提供了一种基本的方法,即(在链接发生变化时从文档中复制):

import gdata.spreadsheet
import gdata.spreadsheet.service

client = gdata.spreadsheet.service.SpreadsheetsService()
# Authenticate ...

cells = client.GetCellsFeed('your_spreadsheet_key', wksht_id='your_worksheet_id')

batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed()

cells.entry[0].cell.inputValue = 'x'
batchRequest.AddUpdate(cells.entry[0])
cells.entry[1].cell.inputValue = 'y'
batchRequest.AddUpdate(cells.entry[1])
cells.entry[2].cell.inputValue = 'z'
batchRequest.AddUpdate(cells.entry[2])
cells.entry[3].cell.inputValue = '=sum(3,5)'
batchRequest.AddUpdate(cells.entry[3])

updated = client.ExecuteBatch(batchRequest, cells.GetBatchLink().href)