简体   繁体   中英

Grabbing a Chart as image via JS script and Google Sheets API?

I'm creating a Discord Bot that will grab a specified chart from a Google Sheet and send the chart to the server. The sheet on hand will only ever have one chart at a time, so I've been able to find the correct chartId as follows:

sheets.spreadsheets.get({
    spreadsheetId: 'MYSPREADSHEETID'
}, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    var id = res.data.sheets[0].charts[0].chartId;
});

However, I cannot find out how to export the corresponding chart as an image, or find a unique URL to the chart, or even recreate the chart using the existing data. I'm using discord.js and Google Sheets API v4.

At the moment of this post, unfortunately it is not possible to retrieve a chart as an image or get its specifc URL with Sheets API. Here I present three workarounds when we encounter the issue of trying to retrieve the image of a chart in a spreadsheet.

Workaround 1

If your main intention is to get the chart data to then use it somewhere else or create a data Blob with it for other Google Applications, you can use the API method GET requesting only the desired fields (in our case, the chart objects) as shown in this example of the documentation .

Workaround 2

If what you need is to easily access this chart image with a simple link, you could publish your chart following these steps shown in the documentation . This can generate either a link or an embed for your website that you can easily share and use.

Workaround 3

You can use Apps Script to create a Web App and using the API method in the first workaround generate a Blob from the chart object and use it to be inserted as an image either in another sheet or in a HTML page. In this Stack Overflow answer you can see an exmple of the implementation of this workaround.

I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM