Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a list of list in python to google sheets using gspread

I have created a nested list in python which looks like

my_list = [[a,b],[c,d],[e,f],[g,h].....]

What I want to do is insert this list as a batch so that each element gets inserted in a new row in the google sheet. This list is generated from an user input and therefore the number of elements in my_list may vary. The final output should look as follows:

enter image description here

I do not want to do this row by row as the list can be lengthy and there can be many similar lists which will the make the entire process inefficient.

Any help would be greatly appreciated!!

like image 436
Sameera Avatar asked Apr 21 '18 18:04

Sameera


People also ask

How do I insert data into Google Sheets using Python?

Search for 'Google Drive API', enable it. Select Compute Engine service default, JSON, hit create. Open up the JSON file, share your spreadsheet with the "[email protected]" email listed. Save the JSON file wherever you're hosting your project, you'll need to load it in through Python later.

What is GSpread in Python?

gspread is a Python API for Google Sheets. Features: Google Sheets API v4. Open a spreadsheet by title, key or url. Read, write, and format cell ranges.

How do I autofill in Gsheet?

On your Android phone or tablet, open a spreadsheet in the Google Sheets app. In a column or row, enter text, numbers, or dates in at least two cells next to each other. To highlight your cells, drag the corner over the cells you've filled in and the cells you want to autofill. Autofill.


1 Answers

In gspread version 3.0.0 (the latest at the time of writing), the most efficient way to insert a nested list like you described is the following:

my_list = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

sh.values_update(
    'Sheet1!A1', 
    params={'valueInputOption': 'RAW'}, 
    body={'values': my_list}
)

Where sh is an instance of Spreadsheet class and Sheet1 is the name of a sheet you're updating.

This will update the values of cells in one go with a single request to the Sheets API.

Note: in future releases of gspread, there could be an alternative way to do this. Please keep an eye on the repo.

like image 69
Burnash Avatar answered Dec 04 '22 05:12

Burnash