2

I need a way to insert an image into a specific cell in a specific Google Sheet. If there is any python package and/or slice of code that can accomplish this, please let me know. As far as I am aware Gspread does not have anything helpful.

Ivan
  • 41
  • 1
  • 3
  • Can you please provide more details of your code and what is not working for you? To provide more details you can review this guide - https://stackoverflow.com/help/how-to-ask – TomTom Jul 27 '20 at 23:26
  • Sorry if I confused you, I don't have a problem with the code. I want to write a new section of the code, that would add an image to a cell. However, I have no idea how to do that, that is why I asked. I have a Google Sheets API set up and working, all I need now if a way to insert the image. – Ivan Jul 28 '20 at 02:20

3 Answers3

3

You can simply insert an image from an URL with a formula like this:

'=image("https://drive.google.com/uc?export=view&id={}")'.format(file_id)

When you insert/upload the data be sure to choose USER_ENTERED for value input option. https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption

With gspred:

sheet_instance.insert_rows(rows, value_input_option='USER_ENTERED')
Andy
  • 341
  • 5
  • 10
1

Overall to add image into Google Sheets can be accomplished with Python by first inserting the image file in Google Drive using the Google Drive API:

Here is how to insert it to google drive. - https://developers.google.com/drive/v2/reference/files/insert#examples,

and secondly linking to the image in Google Sheets with the Google Sheets API, Here is Google sheets API - https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#CellData

Note: Look under CellData

TomTom
  • 1,113
  • 1
  • 10
  • 20
0

To do so follow these steps :

  • First load the image to the drive and share it
  • Get the file id of your image in the drive
  • Then this is the code using gspread python package:
image_id = "" # put the id
insert_image = '=IMAGE(f"https://drive.google.com/uc?export=view&id={image_id}")'
sheet_range = "" # Add where you want to insert the image for example A2:A2 to insert the image into the cell A2
sheet.update(sheet_range, [[insert_image]], value_input_option="USER_ENTERED")

And that's it (of course you can use any method of gspread based on your need update / update_batch / insert_row etc) but don't forget value_input_option="USER_ENTERED"

Hope this helps

kaouther
  • 369
  • 1
  • 11