Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple rows into google spreadsheet using API

I need to add multiple (few hundreds) rows into google spreadsheet. Currently I'm doing it in a loop:

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

which is extremely slow, because rows are added one by one.

Is there any way to speed this up?

like image 649
damgad Avatar asked Jul 30 '14 14:07

damgad


People also ask

How do I insert multiple rows between data in Google Sheets?

Hold ⇧ Shift and select the number of rows you want to insert. For example, if you want to insert 4 new rows, select the 4 rows above or below where you want to insert them. You can select up to 100 rows. If you want to insert more than 100 rows, you can do so at the bottom of your spreadsheet.

How do I add multiple items in Google Sheets?

Click on Data Validation. In the Data Validation dialog box, make sure the 'Cell range' refers to the cell where you want the drop-down. In Criteria, select 'List from a range' and then select the range that has the items that you want to show in the drop-down. Click on Save.


1 Answers

Ok, I finally used batch request. The idea is to send multiple changes in a one API request.

Firstly, I created a list of dictionaries, which will be used like rows_map[R][C] to get value of cell at row R and column C.

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

Then I get all the cells from the worksheet

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

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

And create batch request to modify multiple cells at a time.

batch_request = gdata.spreadsheet.SpreadsheetsCellsFeed()

Then I can modify (or in my case rewrite all the values) the spreadsheet.

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)

And send all the changes in only one request:

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

NOTES:

Batch request are possible only with Cell Queries. There is no such mechanism to be used with List Queries.

query.return_empty = 'true' is mandatory. Otherwise API will return only cells which are not empty.

like image 80
damgad Avatar answered Sep 19 '22 22:09

damgad