【问题标题】:Add multiple rows into google spreadsheet using API使用 API 将多行添加到谷歌电子表格中
【发布时间】:2014-09-22 05:18:49
【问题描述】:

我需要在谷歌电子表格中添加多行(几百行)。目前我正在循环执行:

for row in rows
   _api_client.InsertRow(row, _spreadsheet_key, _worksheet_id)

这非常慢,因为行是一一添加的。

有什么办法可以加快速度吗?

【问题讨论】:

  • API有“批量更新”,我用Java用过,没看python版本。

标签: python gdata google-spreadsheet-api


【解决方案1】:

好的,我终于使用了批处理请求。这个想法是在一个 API 请求中发送多个更改。

首先,我创建了一个字典列表,将像rows_map[R][C] 一样使用它来获取R 行和C 列的单元格的值。

rows_map = [
    {
        1: row['first_column']
        2: row['second']
        3: row['and_last']
    }
    for row i rows
]

然后我从工作表中获取所有单元格

query = gdata.spreadsheet.service.CellQuery()
query.return_empty = 'true'

cells = _api_client.GetCellsFeed(self._key, wksht_id=self._raw_events_worksheet_id, query=query)

并创建批量请求以一次修改多个单元格。

batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed()

然后我可以修改(或者在我的情况下重写所有值)电子表格。

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)

并在一个请求中发送所有更改:

_api_client.ExecuteBatch(batch_request, cells.GetBatchLink().href)

注意事项:

批量请求仅适用于单元查询。列表查询没有这样的机制。

query.return_empty = 'true' 是必填项。否则 API 将只返回非空单元格。

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多