How to save a googlesheet chart as image by Python

Viewed 40

I'm using Googlesheet API with Python and I can get access to the sheet and the cells now. However, I don't know how to get the chart in the sheet.

client = gspread.service_account_from_dict(creds)
workbook = client.open('HR - 8/16-8/31 Data')
sheet = workbook.get_worksheet(0)
H1 = sheet.acell('B3').value

I found this question:How to download charts in PNG from google sheet mentioned I can use the getCharts() function, but it is for JavaScript only. If there a similar function in Python?

1 Answers

Currently the API doesn't have a method to do this. The charts overview documentation explains how to manipulate and create them, but not how to export them. Reading the data also only gives you a JSON representation of it, not an image. It seems that the Apps Script getCharts() leverages other server-side functions that are not in the regular API.

This is documented as a feature request in Google's issue tracker here, so you can +1 it if you want. In that thread a possible workaround was posted. If you publish your file you can build a URL if you know the chartID to generate it as an image:

https://docs.google.com/spreadsheets/d/e/<publish-id>/pubchart?oid=<chart-id>&format=image

Gspread doesn't seem to have methods to do this so you'll have to use the Google APIs. In their Python Quickstart you can find a sample to set up authorization, and you can use spreadsheets.get(), which gives you all the data from the spreadsheet including the chart IDs. If you only have a single chart that you want to export periodically then you can just get the ID once from the UI and just retrieve it with Python. The caveat is that you have to publish the Sheet which you don't want to do with sensitive information.

As another alternative you could build an Apps Script Web App which uses the getCharts() method in the answer that you linked, and just send a POST message from your Python app and have Apps Script return the image in its response.

Related