dam*_*gad 5 python gdata google-spreadsheet-api
我需要在google电子表格中添加多行(几百行).目前我正在循环中这样做:
for row in rows
_api_client.InsertRow(row, _spreadsheet_key, _worksheet_id)
Run Code Online (Sandbox Code Playgroud)
这是非常慢的,因为行是逐个添加的.
有什么方法可以加快速度吗?
好的,我终于使用了批量请求.我们的想法是在一个API请求中发送多个更改.
首先,我创建了一个字典列表,用于rows_map[R][C]获取行R和列的单元格值C.
rows_map = [
{
1: row['first_column']
2: row['second']
3: row['and_last']
}
for row i rows
]
Run Code Online (Sandbox Code Playgroud)
然后我从工作表中获取所有单元格
query = gdata.spreadsheet.service.CellQuery()
query.return_empty = 'true'
cells = _api_client.GetCellsFeed(self._key, wksht_id=self._raw_events_worksheet_id, query=query)
Run Code Online (Sandbox Code Playgroud)
并创建批处理请求以一次修改多个单元格.
batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed()
Run Code Online (Sandbox Code Playgroud)
然后我可以修改(或在我的情况下重写所有值)电子表格.
for cell_entry in cells.entry:
row = int(cell_entry.cell.row) - 2
col = int(cell_entry.cell.col)
if 0 <= row < len(events_map):
cell_entry.cell.inputValue = rows_map[row][col]
else:
cell_entry.cell.inputValue = ''
batch_request.AddUpdate(cell_entry)
Run Code Online (Sandbox Code Playgroud)
并仅在一个请求中发送所有更改:
_api_client.ExecuteBatch(batch_request, cells.GetBatchLink().href)
Run Code Online (Sandbox Code Playgroud)
笔记:
批量请求仅适用于单元格查询.没有这种机制可以与List Queries一起使用.
query.return_empty = 'true'是强制性的.否则API将仅返回非空的单元格.
| 归档时间: |
|
| 查看次数: |
1896 次 |
| 最近记录: |