The new function Insert > Image > Image in Cell in Google sheets inserts an image in a cell and not as an OverGridImage.
I would like to insert the image in this manner and then access the image from Google Apps Script. Is this possible?
After inserting the image the formula of the cell is blank when the cell is selected. I tried searching the GAS reference, but I could not find any information on this relatively new feature.
There is information on the over grid images. I would expect the in-cell image to have similar functions.
I've tried things like this:
// See what information is available on a cell with inserted image:
var image = sheet.getRange(1, 1).getFormula();
Logger.log(image);
The logs shows up empty.
I tried several: .getImage() (does not exist), .getValue(), .getFormula()
I would expect to be able to access the image URL or Blob in some way.
Answer:
This is a new feature and unfortunately at current there isn’t a method to be able to get an image inserted into a Cell this way using Google Apps Script, nor using the Sheets API.
More Information:
Attempting to get the data in a cell using the spreadsheets.get method with the following parameters
spreadsheetId: "ID of private spreadsheet created in Drive"
includeGridData: True
ranges: D7
fields: sheets/data/rowData/values
Will return a 200 response, however the image data is not returned:
{
"sheets": [
{
"data": [
{
"rowData": [
{
"values": [
{
"userEnteredValue": {},
"effectiveValue": {},
"effectiveFormat": {
"backgroundColor": {
"red": 1,
"green": 1,
"blue": 1
},
"padding": {
"top": 2,
"right": 3,
"bottom": 2,
"left": 3
},
"horizontalAlignment": "LEFT",
"verticalAlignment": "BOTTOM",
"wrapStrategy": "OVERFLOW_CELL",
"textFormat": {
"foregroundColor": {},
"fontFamily": "Arial",
"fontSize": 10,
"bold": false,
"italic": false,
"strikethrough": false,
"underline": false
},
"hyperlinkDisplayType": "PLAIN_TEXT"
}
}
]
}
]
}
]
}
]
}
Feature Request:
There is however a Feature request for this on Google’s Issue Tracker which you can find here. If you head over to the feature request page and click the star in the top left, you can let Google know that you also would like this feature, and will automatically get updates about its progress.
I believe your goal as follows.
You want to retrieve the image in the cell of Google Spreadsheet using Google Apps Script.
Issue and workaround:
Unfortunately, in the current stage, there are no methods for retrieving the images in the cell on Spreadsheet in Spreadsheet service and Sheets API. This has already been mentioned by Rafa Guillermo's answer. So in this answer, I would like to propose a workaround for retrieving the images in the cells using Google Apps Script.
In this workaround, I use Microsoft Excel Data converted from Google Spreadsheet. Even when Google Spreadsheet is converted to Microsoft Excel Data, the images in the cells are not removed. I use this. Of course, the images can be also retrieved from HTML data converted from Spreadsheet. But in this case, the parse of HTML data is a bit complicated than that of Excel data. So here, I would like to propose to retrieve the images from Excel Data converted from Spreadsheet. The flow of this workaround is as follows.
Convert Google Spreadsheet to Microsoft Excel (XLSX data) using Drive API.
Parse XLSX data using Google Apps Script.
When the converted XLSX data is unzipped, the data can be analyzed as the XML data. Fortunately, at Microsoft Docs, the detail specification is published as Open XML. So in this case, Microsoft Docs like XLSX, DOCX and PPTX can be analyzed using XmlService of Google Apps Script. I think that this method will be also useful for other situations.
Retrieve images from XLSX data.
Pattern 1:
In this pattern, I would like to introduce a simple method.
Sample script:
function myFunction() {
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + spreadsheetId;
const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob().setContentType(MimeType.ZIP);
const xlsx = Utilities.unzip(blob);
xlsx.forEach(b => {
const name = b.getName().match(/xl\/media\/(.+)/);
if (name) DriveApp.createFile(b.setName(name[1]));
});
}
In this sample script, all images in the Spreadsheet are exported as the files. So in this case, both images in the cells and over the cells from all sheets in the Spreadsheet are retrieved. And also, it cannot retrieve the cell coordinate that the image is in the cell.
In the current stage, there are no methods for retrieving the images in Google Spreadsheet as the blob. In this sample script, this can be achieved.
This sample script cannot export the drawings. Please be careful this.
When setContentType(MimeType.ZIP) is not used, an error occurs at Utilities.unzip(blob). Please be careful this.
Pattern 2:
In this pattern, the images are retrieved with the sheet name and cell coordinate from Spreadsheet. In this case, the script becomes a bit complicated. So here, I would like to introduce the sample script using a Google Apps Script library. Ref Of course, you can see the whole script there.
Sample script:
Before you use this script, please install DocsServiceApp (The author of this GAS library is tanaike.) of the Google Apps Script library. Ref And run the function of myFunction.
function myFunction() {
const cell = "A1";
const sheetName = "Sheet1";
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const obj = DocsServiceApp.openBySpreadsheetId(spreadsheetId).getSheetByName(sheetName).getImages();
console.log(obj)
const blobs = obj.filter(({range, image}) => range.a1Notation == cell && image.innerCell);
console.log(blobs.length)
if (blobs.length > 0) DriveApp.createFile(blobs[0].image.blob);
}
In this sample, the image in the cell "A1" of "Sheet1" in the active Spreadsheet is retrieved, and the retrieved blob is created to the root folder as an image file.
Note:
In the current stage, when an image is inserted to Google Spreadsheet and the Spreadsheet is converted to XLSX data, the image including the XLSX data has the filename of image1, image2,,, which are not the original filename. So it seems that this is the current specification.
When the images are retrieved from XLSX data, it seems that the image is a bit different from the original one. The image format is the same. But the data size is smaller than that of the original. When the image size is more than 2048 pixels and 72 dpi, the image is modified to 2048 pixels and 72 dpi. Even when the image size is less than 2048 pixels and 72 dpi, the file size becomes smaller than that of original one. So I think that the image might be compressed. Please be careful this.
In the current stage, the drawings cannot be directly retrieved.
References:
Understanding the Open XML file formats
XML Service
DocsServiceApp
Now available as of January 2022 (release notes):
The following classes have been added to the Spreadsheet Service to let you add images to cells:
CellImageBuilder: This builder creates the image value needed to add an image to a >cell.
CellImage: Represents an image to add to a cell.
To add an image to a cell, you must create a new image value for the image using SpreadsheetApp.newCellImage() and CellImageBuilder. Then, use Range.setValue(value) or Range.setValues(values) to add the image value to the cell.
Example:
function insertImageIntoCell()
{
let image = SpreadsheetApp.newCellImage().setSourceUrl('https://www.gstatic.com/images/branding/product/2x/apps_script_48dp.png').setAltTextDescription('Google Apps Script logo').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('A1').setValue(image);
}
Result:
function getImageFromCell()
{
let value = SpreadsheetApp.getActive().getActiveSheet().getRange('A1').getValue();
console.log(value.getAltTextDescription());
console.log(value.getUrl());
}
Result:
Note: getUrl returns null for this particular example, which seems to be due some internal API unavailability, from docs:
Gets the image's source URL; returns null if the URL is unavailable. If the image was inserted by URL using an API, this method returns the URL provided during image insertion.
This answer is about INSERTING in-cell images. I haven't been able to find a way to actually extract image data so Panos's answer is the best option for reading in-cell image data.
There are a few different ways to do this, some of them use some undocumented APIs.
1. =IMAGE(<http url>)
The =IMAGE is a standard function which displays in image within a cell. It does almost the exact same thing as manually inserting an in-cell image.
2. Copied-by-value =IMAGE
Once you have an =IMAGE image you can copy it and paste it by-value which will duplicate the image without the formula (if you want that for some reason). You can do this in a script using the copyTo function:
srcImageRange.copyTo(dstRange, { contentsOnly: true })
This formula-less IMAGE is only distinguishable from a true in-cell image in that when you right-click on it is missing the "Alt text" and "Put image over cells" context menu options. Those options only show up on real in-cell images.
3. The undocumented CellImage APIs
When you call getValue() on a in-cell image (both formula and manually inserted) you get a CellImage instance.
CellImage
Prop/method
(Return) Type
Description
toString()
string
returns "CellImage".
getContentUrl()
?
always throws an error?
toBuilder()
CellImageBuilder
Convert this into an writable CellImageBuilder instance.
getAltTextDescription()
string
Returns the alt text description.
getAltTextTitle()
string
Returns the alt text title.
getUrl()
?
Doesn't seem to work, always returns undefined. :(
valueType
?
Same as SpreadsheetApp.ValueType, doesn't seem meaningful.
CellImageBuilder
Has all the same properties and methods as CellImage with these additional ones:
Prop/method
(Return) Type
Description
toString()
string
returns "CellImageBuilder".
build()
CellImage
Convert into a (read-only) CellImage instance.
setSourceUrl(string)
void
Update the image by supplying a web or data URL.
setAltTextTitle(string)
void
Sets the alt text title.
setAltTextDescription(string)
void
Sets the alt text description.
The major benefit I see with using this over IMAGE() is that it supports data URLs and therefore indirectly supports blobs.
Working Example Code
Keep in mind the undocumented APIs might change without notice.
Link to Example Spreadhseet
// 1 (or just use IMAGE in formula directly)
function insertImageFormula(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
}
// 2
function insertImageValue(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
SpreadsheetApp.flush(); // Flush needed for image to load.
range.copyTo(range, { contentsOnly: true }); // Copy value onto itself, removing the formula.
}
// 3
function insertCellImage(range, sourceUrl) {
range.setFormula('=IMAGE("http")'); // Set blank image to get CellImageBuilder handle.
const builder = range.getValue().toBuilder();
builder.setSourceUrl(sourceUrl);
builder.setAltTextDescription(sourceUrl); // Put url in description for later identification, for example.
range.setValue(builder.build());
}
const DATA_URI = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7///"
+ "/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAos"
+ "J6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
function test() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.clear();
sheet.getRange(1, 1).setValue("IMAGE formula");
insertImageFormula(sheet.getRange(2, 1), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 2).setValue("Copied-by-value IMAGE");
insertImageValue(sheet.getRange(2, 2), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 3).setValue("In-Cell Image (Http URL)");
insertCellImage(sheet.getRange(2, 3), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 4).setValue("In-Cell Image (DATA URI)");
insertCellImage(sheet.getRange(2, 4), DATA_URI);
sheet.getRange(1, 5).setValue("In-Cell Image (Blob DATA URI)");
const blob = UrlFetchApp.fetch("https://www.gstatic.com/script/apps_script_1x_24dp.png").getBlob();
insertCellImage(sheet.getRange(2, 5), blobToDataUrl(blob));
}
function blobToDataUrl(blob) {
return `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`
}
Both Rafa Guillermo and Tanaike requested that I make an answer based on my comment to Tanaike’s post. I do so below, but it falls into the category of a workaround rather than an "answer". A true answer would address the exact question in the original post.
As I said in my comment, I’ve used this method for simple cases, and I’ve also done some tests which suggest it preserves image resolution. Since I've only used this for simple cases like the one below, I don't know how generally it will work.
The steps I provide below are (to the best of my ability) what I remember going through as I did one specific example. Here are the first dozen rows of the final result after using this method:
This example had a total of 7100+ rows
Column 1 contained 430+ images or blank cells, most of which repeated
multiple times
Column 2 contained unique IDs for each image
Column 3 are the file names which were tied to each ID using the
method below
Steps to extract images from google sheet cells:
Resize column and rows containing images to something large (eg, 300)
Use File>Publish to Web & paste generated link into a new tab
In Chrome, use File>Save Page As…>Webpage, Complete
Images will be found in an html folder ending with _files
If needed, rename files to use image extension and list in order*
To key downloaded image file names to image cells in the sheet:
Duplicate sheet since the following will remove original data
Select columns containing images and IDs and use Data>Remove Duplicates
Add a new column next to the IDs containing the file names**
Use VLOOKUP function to transfer all file names to original sheet based on the unique IDs***
*In my example the images all had names like p.txt, p(1).txt, p(2).txt, etc… In Mac OS Finder, I selected all files and used right click>Rename files… and then the replace option to replace .txt with .jpg, (1) with (001), etc…
**file name listing can be obtained, for example, using the Terminal ls -l command
***for example, I used: =vlookup(B2,unique!$B$2:$C$430,2,false)
This question is a little old, but since I faced today this problem, please allow me to share my experience.
I realized that the getValue() of the cell, returns an object that its text is "CellImage". This allows me to understand that there is an embedded image in this cell. This objects seems to be similar to (or the same) with the OverGridImage object. At least, you can use the getAltTextTitle and the getAltTextDescription methods.
By combining all these features, my workaround is:
Add specific AltText to the image in the cell.
Get the value of the cell in an object.
Check if this is equals to "CellImage".
If it is CellImage, get the AltText.
Based on the value of this AltText do whatever you like.
The sample code follows:
/*-------------------------------------------------------------------------
Custom event handler triggered when a single cell is selected in the spreadsheet.
#param {Event} e The onSelectionChange event.
-------------------------------------------------------------------------*/
function onSingleCellSelected(e) {
var cell = e.range.getCell(1, 1);
var v = cell.getValue();
if(v == "CellImage") {
var altText = v.getAltTextTitle();
Logger.log(v.getAltTextDescription());
if(altText == "#action(recordTime)"){
cell.setBackground("cyan");
}
}
}
I just tried something pretty basic and it worked. Maybe doesn't work in all cases, depends if you added the images previously through a formula...
Add image through Google Apps Script :
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
sheet.getRange('A1').setFormula('=IMAGE("https://developers.google.com/google-ads/scripts/images/reports.png")');
Worked (it's in the cell and will work auto fit on resizing) :
Then to retrieve the image url from cell :
var imgVal = sheet.getRange('A1').getFormula();
var regEx = /"(.*)"/gm;
var url = regEx.exec(imgVal)[1];
Logger.log(url);
Logs will be :
Related
Trying to get image url in google script.
couldn’t find any function that is able to get the url from images that are not in a specific cell, images are located above the grid.
any ideas?
Issue and workaround:
On October 30, 2018, in order to manage the images on the cells in Spreadsheet, a new Class of OverGridImage has been added. Ref By this, the images on the cells got to be able to be managed. This class has the method of getUrl. The official document of this method says as follows.
Gets the image's source URL; returns null if the URL is unavailable. If the image was inserted by URL using an API, this method returns the URL provided during image insertion.
Namely, for example, when the following script is run, the URL of the image can be retrieved.
function sample1() {
const sheet = SpreadsheetApp.getActiveSheet();
// Put image from URL.
sheet.insertImage("https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png", 1, 1);
// Retrieve image URL.
const images = sheet.getImages();
const url = images[0].getUrl();
console.log(url)
}
In your actual situation, if your images are put on the cells using the above script, the URLs can be retrieved by the above simple script. But, here, there is an important point. After the image was put using this script, when you manually move the image, the URL cannot be retrieved. I think that this is a bug.
And also, if you had manually put the images from the URL and your drive, unfortunately, the URL of the images cannot be retrieved. About this, it has already been reported to the Google issue tracker. Ref
If you had manually put the images from the URL and your drive, and when you want to retrieve the URLs of the images, it is required to use a workaround. In this case, I would like to propose to use this method of this answer. In this answer, my created Google Apps Script library is used.
Usage:
1. Install Google Apps Script library.
You can see the method for installing this library at here.
2. Enable Drive API.
In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
3. Sample script.
function sample2() {
const sheetName = "Sheet1"; // Please set the sheet name.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const images = sheet.getImages();
const obj = images.reduce((o, e) => {
const u = e.getUrl();
if (u) o[e.getAnchorCell().getA1Notation()] = u;
return o;
}, {});
const res = DocsServiceApp.openBySpreadsheetId(ss.getId()).getSheetByName(sheetName).getImages();
if (res.length == 0) return;
const urls = res.map(({ image, range }, i) => {
if (obj[range.a1Notation]) return obj[range.a1Notation];
const o = Drive.Files.insert({ title: `sample${i + 1}` }, image.blob);
const url = o.thumbnailLink.replace(/\=s\d+/, "=s1000");
DriveApp.getFileById(o.id).setTrashed(true);
return url;
});
console.log(urls)
}
4. Testing.
When the above script is run, the images are retrieved from "Sheet1" and retrieve the URLs of the images. For example, when there are images put with the image URL using the script, the URL can be retrieved.
Note:
In this workaround, in order to retrieve the URL of the image, the thumbnail link is used. This link is not permanent. Please be careful about this. If you are required to retrieve the permanent link, please create the retrieved image file blob as the file, and please publicly share them, and then, please retrieve the WebContentLink. By this, you can retrieve the permanent link of the image.
References:
DocsServiceApp
Related thread
How to access new 'in-cell-image' from google apps script?
The new function Insert > Image > Image in Cell in Google sheets inserts an image in a cell and not as an OverGridImage.
I would like to insert the image in this manner and then access the image from Google Apps Script. Is this possible?
After inserting the image the formula of the cell is blank when the cell is selected. I tried searching the GAS reference, but I could not find any information on this relatively new feature.
There is information on the over grid images. I would expect the in-cell image to have similar functions.
I've tried things like this:
// See what information is available on a cell with inserted image:
var image = sheet.getRange(1, 1).getFormula();
Logger.log(image);
The logs shows up empty.
I tried several: .getImage() (does not exist), .getValue(), .getFormula()
I would expect to be able to access the image URL or Blob in some way.
Answer:
This is a new feature and unfortunately at current there isn’t a method to be able to get an image inserted into a Cell this way using Google Apps Script, nor using the Sheets API.
More Information:
Attempting to get the data in a cell using the spreadsheets.get method with the following parameters
spreadsheetId: "ID of private spreadsheet created in Drive"
includeGridData: True
ranges: D7
fields: sheets/data/rowData/values
Will return a 200 response, however the image data is not returned:
{
"sheets": [
{
"data": [
{
"rowData": [
{
"values": [
{
"userEnteredValue": {},
"effectiveValue": {},
"effectiveFormat": {
"backgroundColor": {
"red": 1,
"green": 1,
"blue": 1
},
"padding": {
"top": 2,
"right": 3,
"bottom": 2,
"left": 3
},
"horizontalAlignment": "LEFT",
"verticalAlignment": "BOTTOM",
"wrapStrategy": "OVERFLOW_CELL",
"textFormat": {
"foregroundColor": {},
"fontFamily": "Arial",
"fontSize": 10,
"bold": false,
"italic": false,
"strikethrough": false,
"underline": false
},
"hyperlinkDisplayType": "PLAIN_TEXT"
}
}
]
}
]
}
]
}
]
}
Feature Request:
There is however a Feature request for this on Google’s Issue Tracker which you can find here. If you head over to the feature request page and click the star in the top left, you can let Google know that you also would like this feature, and will automatically get updates about its progress.
I believe your goal as follows.
You want to retrieve the image in the cell of Google Spreadsheet using Google Apps Script.
Issue and workaround:
Unfortunately, in the current stage, there are no methods for retrieving the images in the cell on Spreadsheet in Spreadsheet service and Sheets API. This has already been mentioned by Rafa Guillermo's answer. So in this answer, I would like to propose a workaround for retrieving the images in the cells using Google Apps Script.
In this workaround, I use Microsoft Excel Data converted from Google Spreadsheet. Even when Google Spreadsheet is converted to Microsoft Excel Data, the images in the cells are not removed. I use this. Of course, the images can be also retrieved from HTML data converted from Spreadsheet. But in this case, the parse of HTML data is a bit complicated than that of Excel data. So here, I would like to propose to retrieve the images from Excel Data converted from Spreadsheet. The flow of this workaround is as follows.
Convert Google Spreadsheet to Microsoft Excel (XLSX data) using Drive API.
Parse XLSX data using Google Apps Script.
When the converted XLSX data is unzipped, the data can be analyzed as the XML data. Fortunately, at Microsoft Docs, the detail specification is published as Open XML. So in this case, Microsoft Docs like XLSX, DOCX and PPTX can be analyzed using XmlService of Google Apps Script. I think that this method will be also useful for other situations.
Retrieve images from XLSX data.
Pattern 1:
In this pattern, I would like to introduce a simple method.
Sample script:
function myFunction() {
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + spreadsheetId;
const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob().setContentType(MimeType.ZIP);
const xlsx = Utilities.unzip(blob);
xlsx.forEach(b => {
const name = b.getName().match(/xl\/media\/(.+)/);
if (name) DriveApp.createFile(b.setName(name[1]));
});
}
In this sample script, all images in the Spreadsheet are exported as the files. So in this case, both images in the cells and over the cells from all sheets in the Spreadsheet are retrieved. And also, it cannot retrieve the cell coordinate that the image is in the cell.
In the current stage, there are no methods for retrieving the images in Google Spreadsheet as the blob. In this sample script, this can be achieved.
This sample script cannot export the drawings. Please be careful this.
When setContentType(MimeType.ZIP) is not used, an error occurs at Utilities.unzip(blob). Please be careful this.
Pattern 2:
In this pattern, the images are retrieved with the sheet name and cell coordinate from Spreadsheet. In this case, the script becomes a bit complicated. So here, I would like to introduce the sample script using a Google Apps Script library. Ref Of course, you can see the whole script there.
Sample script:
Before you use this script, please install DocsServiceApp (The author of this GAS library is tanaike.) of the Google Apps Script library. Ref And run the function of myFunction.
function myFunction() {
const cell = "A1";
const sheetName = "Sheet1";
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const obj = DocsServiceApp.openBySpreadsheetId(spreadsheetId).getSheetByName(sheetName).getImages();
console.log(obj)
const blobs = obj.filter(({range, image}) => range.a1Notation == cell && image.innerCell);
console.log(blobs.length)
if (blobs.length > 0) DriveApp.createFile(blobs[0].image.blob);
}
In this sample, the image in the cell "A1" of "Sheet1" in the active Spreadsheet is retrieved, and the retrieved blob is created to the root folder as an image file.
Note:
In the current stage, when an image is inserted to Google Spreadsheet and the Spreadsheet is converted to XLSX data, the image including the XLSX data has the filename of image1, image2,,, which are not the original filename. So it seems that this is the current specification.
When the images are retrieved from XLSX data, it seems that the image is a bit different from the original one. The image format is the same. But the data size is smaller than that of the original. When the image size is more than 2048 pixels and 72 dpi, the image is modified to 2048 pixels and 72 dpi. Even when the image size is less than 2048 pixels and 72 dpi, the file size becomes smaller than that of original one. So I think that the image might be compressed. Please be careful this.
In the current stage, the drawings cannot be directly retrieved.
References:
Understanding the Open XML file formats
XML Service
DocsServiceApp
Now available as of January 2022 (release notes):
The following classes have been added to the Spreadsheet Service to let you add images to cells:
CellImageBuilder: This builder creates the image value needed to add an image to a >cell.
CellImage: Represents an image to add to a cell.
To add an image to a cell, you must create a new image value for the image using SpreadsheetApp.newCellImage() and CellImageBuilder. Then, use Range.setValue(value) or Range.setValues(values) to add the image value to the cell.
Example:
function insertImageIntoCell()
{
let image = SpreadsheetApp.newCellImage().setSourceUrl('https://www.gstatic.com/images/branding/product/2x/apps_script_48dp.png').setAltTextDescription('Google Apps Script logo').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('A1').setValue(image);
}
Result:
function getImageFromCell()
{
let value = SpreadsheetApp.getActive().getActiveSheet().getRange('A1').getValue();
console.log(value.getAltTextDescription());
console.log(value.getUrl());
}
Result:
Note: getUrl returns null for this particular example, which seems to be due some internal API unavailability, from docs:
Gets the image's source URL; returns null if the URL is unavailable. If the image was inserted by URL using an API, this method returns the URL provided during image insertion.
This answer is about INSERTING in-cell images. I haven't been able to find a way to actually extract image data so Panos's answer is the best option for reading in-cell image data.
There are a few different ways to do this, some of them use some undocumented APIs.
1. =IMAGE(<http url>)
The =IMAGE is a standard function which displays in image within a cell. It does almost the exact same thing as manually inserting an in-cell image.
2. Copied-by-value =IMAGE
Once you have an =IMAGE image you can copy it and paste it by-value which will duplicate the image without the formula (if you want that for some reason). You can do this in a script using the copyTo function:
srcImageRange.copyTo(dstRange, { contentsOnly: true })
This formula-less IMAGE is only distinguishable from a true in-cell image in that when you right-click on it is missing the "Alt text" and "Put image over cells" context menu options. Those options only show up on real in-cell images.
3. The undocumented CellImage APIs
When you call getValue() on a in-cell image (both formula and manually inserted) you get a CellImage instance.
CellImage
Prop/method
(Return) Type
Description
toString()
string
returns "CellImage".
getContentUrl()
?
always throws an error?
toBuilder()
CellImageBuilder
Convert this into an writable CellImageBuilder instance.
getAltTextDescription()
string
Returns the alt text description.
getAltTextTitle()
string
Returns the alt text title.
getUrl()
?
Doesn't seem to work, always returns undefined. :(
valueType
?
Same as SpreadsheetApp.ValueType, doesn't seem meaningful.
CellImageBuilder
Has all the same properties and methods as CellImage with these additional ones:
Prop/method
(Return) Type
Description
toString()
string
returns "CellImageBuilder".
build()
CellImage
Convert into a (read-only) CellImage instance.
setSourceUrl(string)
void
Update the image by supplying a web or data URL.
setAltTextTitle(string)
void
Sets the alt text title.
setAltTextDescription(string)
void
Sets the alt text description.
The major benefit I see with using this over IMAGE() is that it supports data URLs and therefore indirectly supports blobs.
Working Example Code
Keep in mind the undocumented APIs might change without notice.
Link to Example Spreadhseet
// 1 (or just use IMAGE in formula directly)
function insertImageFormula(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
}
// 2
function insertImageValue(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
SpreadsheetApp.flush(); // Flush needed for image to load.
range.copyTo(range, { contentsOnly: true }); // Copy value onto itself, removing the formula.
}
// 3
function insertCellImage(range, sourceUrl) {
range.setFormula('=IMAGE("http")'); // Set blank image to get CellImageBuilder handle.
const builder = range.getValue().toBuilder();
builder.setSourceUrl(sourceUrl);
builder.setAltTextDescription(sourceUrl); // Put url in description for later identification, for example.
range.setValue(builder.build());
}
const DATA_URI = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7///"
+ "/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAos"
+ "J6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
function test() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.clear();
sheet.getRange(1, 1).setValue("IMAGE formula");
insertImageFormula(sheet.getRange(2, 1), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 2).setValue("Copied-by-value IMAGE");
insertImageValue(sheet.getRange(2, 2), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 3).setValue("In-Cell Image (Http URL)");
insertCellImage(sheet.getRange(2, 3), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 4).setValue("In-Cell Image (DATA URI)");
insertCellImage(sheet.getRange(2, 4), DATA_URI);
sheet.getRange(1, 5).setValue("In-Cell Image (Blob DATA URI)");
const blob = UrlFetchApp.fetch("https://www.gstatic.com/script/apps_script_1x_24dp.png").getBlob();
insertCellImage(sheet.getRange(2, 5), blobToDataUrl(blob));
}
function blobToDataUrl(blob) {
return `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`
}
Both Rafa Guillermo and Tanaike requested that I make an answer based on my comment to Tanaike’s post. I do so below, but it falls into the category of a workaround rather than an "answer". A true answer would address the exact question in the original post.
As I said in my comment, I’ve used this method for simple cases, and I’ve also done some tests which suggest it preserves image resolution. Since I've only used this for simple cases like the one below, I don't know how generally it will work.
The steps I provide below are (to the best of my ability) what I remember going through as I did one specific example. Here are the first dozen rows of the final result after using this method:
This example had a total of 7100+ rows
Column 1 contained 430+ images or blank cells, most of which repeated
multiple times
Column 2 contained unique IDs for each image
Column 3 are the file names which were tied to each ID using the
method below
Steps to extract images from google sheet cells:
Resize column and rows containing images to something large (eg, 300)
Use File>Publish to Web & paste generated link into a new tab
In Chrome, use File>Save Page As…>Webpage, Complete
Images will be found in an html folder ending with _files
If needed, rename files to use image extension and list in order*
To key downloaded image file names to image cells in the sheet:
Duplicate sheet since the following will remove original data
Select columns containing images and IDs and use Data>Remove Duplicates
Add a new column next to the IDs containing the file names**
Use VLOOKUP function to transfer all file names to original sheet based on the unique IDs***
*In my example the images all had names like p.txt, p(1).txt, p(2).txt, etc… In Mac OS Finder, I selected all files and used right click>Rename files… and then the replace option to replace .txt with .jpg, (1) with (001), etc…
**file name listing can be obtained, for example, using the Terminal ls -l command
***for example, I used: =vlookup(B2,unique!$B$2:$C$430,2,false)
This question is a little old, but since I faced today this problem, please allow me to share my experience.
I realized that the getValue() of the cell, returns an object that its text is "CellImage". This allows me to understand that there is an embedded image in this cell. This objects seems to be similar to (or the same) with the OverGridImage object. At least, you can use the getAltTextTitle and the getAltTextDescription methods.
By combining all these features, my workaround is:
Add specific AltText to the image in the cell.
Get the value of the cell in an object.
Check if this is equals to "CellImage".
If it is CellImage, get the AltText.
Based on the value of this AltText do whatever you like.
The sample code follows:
/*-------------------------------------------------------------------------
Custom event handler triggered when a single cell is selected in the spreadsheet.
#param {Event} e The onSelectionChange event.
-------------------------------------------------------------------------*/
function onSingleCellSelected(e) {
var cell = e.range.getCell(1, 1);
var v = cell.getValue();
if(v == "CellImage") {
var altText = v.getAltTextTitle();
Logger.log(v.getAltTextDescription());
if(altText == "#action(recordTime)"){
cell.setBackground("cyan");
}
}
}
I just tried something pretty basic and it worked. Maybe doesn't work in all cases, depends if you added the images previously through a formula...
Add image through Google Apps Script :
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
sheet.getRange('A1').setFormula('=IMAGE("https://developers.google.com/google-ads/scripts/images/reports.png")');
Worked (it's in the cell and will work auto fit on resizing) :
Then to retrieve the image url from cell :
var imgVal = sheet.getRange('A1').getFormula();
var regEx = /"(.*)"/gm;
var url = regEx.exec(imgVal)[1];
Logger.log(url);
Logs will be :
The new function Insert > Image > Image in Cell in Google sheets inserts an image in a cell and not as an OverGridImage.
I would like to insert the image in this manner and then access the image from Google Apps Script. Is this possible?
After inserting the image the formula of the cell is blank when the cell is selected. I tried searching the GAS reference, but I could not find any information on this relatively new feature.
There is information on the over grid images. I would expect the in-cell image to have similar functions.
I've tried things like this:
// See what information is available on a cell with inserted image:
var image = sheet.getRange(1, 1).getFormula();
Logger.log(image);
The logs shows up empty.
I tried several: .getImage() (does not exist), .getValue(), .getFormula()
I would expect to be able to access the image URL or Blob in some way.
Answer:
This is a new feature and unfortunately at current there isn’t a method to be able to get an image inserted into a Cell this way using Google Apps Script, nor using the Sheets API.
More Information:
Attempting to get the data in a cell using the spreadsheets.get method with the following parameters
spreadsheetId: "ID of private spreadsheet created in Drive"
includeGridData: True
ranges: D7
fields: sheets/data/rowData/values
Will return a 200 response, however the image data is not returned:
{
"sheets": [
{
"data": [
{
"rowData": [
{
"values": [
{
"userEnteredValue": {},
"effectiveValue": {},
"effectiveFormat": {
"backgroundColor": {
"red": 1,
"green": 1,
"blue": 1
},
"padding": {
"top": 2,
"right": 3,
"bottom": 2,
"left": 3
},
"horizontalAlignment": "LEFT",
"verticalAlignment": "BOTTOM",
"wrapStrategy": "OVERFLOW_CELL",
"textFormat": {
"foregroundColor": {},
"fontFamily": "Arial",
"fontSize": 10,
"bold": false,
"italic": false,
"strikethrough": false,
"underline": false
},
"hyperlinkDisplayType": "PLAIN_TEXT"
}
}
]
}
]
}
]
}
]
}
Feature Request:
There is however a Feature request for this on Google’s Issue Tracker which you can find here. If you head over to the feature request page and click the star in the top left, you can let Google know that you also would like this feature, and will automatically get updates about its progress.
I believe your goal as follows.
You want to retrieve the image in the cell of Google Spreadsheet using Google Apps Script.
Issue and workaround:
Unfortunately, in the current stage, there are no methods for retrieving the images in the cell on Spreadsheet in Spreadsheet service and Sheets API. This has already been mentioned by Rafa Guillermo's answer. So in this answer, I would like to propose a workaround for retrieving the images in the cells using Google Apps Script.
In this workaround, I use Microsoft Excel Data converted from Google Spreadsheet. Even when Google Spreadsheet is converted to Microsoft Excel Data, the images in the cells are not removed. I use this. Of course, the images can be also retrieved from HTML data converted from Spreadsheet. But in this case, the parse of HTML data is a bit complicated than that of Excel data. So here, I would like to propose to retrieve the images from Excel Data converted from Spreadsheet. The flow of this workaround is as follows.
Convert Google Spreadsheet to Microsoft Excel (XLSX data) using Drive API.
Parse XLSX data using Google Apps Script.
When the converted XLSX data is unzipped, the data can be analyzed as the XML data. Fortunately, at Microsoft Docs, the detail specification is published as Open XML. So in this case, Microsoft Docs like XLSX, DOCX and PPTX can be analyzed using XmlService of Google Apps Script. I think that this method will be also useful for other situations.
Retrieve images from XLSX data.
Pattern 1:
In this pattern, I would like to introduce a simple method.
Sample script:
function myFunction() {
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + spreadsheetId;
const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob().setContentType(MimeType.ZIP);
const xlsx = Utilities.unzip(blob);
xlsx.forEach(b => {
const name = b.getName().match(/xl\/media\/(.+)/);
if (name) DriveApp.createFile(b.setName(name[1]));
});
}
In this sample script, all images in the Spreadsheet are exported as the files. So in this case, both images in the cells and over the cells from all sheets in the Spreadsheet are retrieved. And also, it cannot retrieve the cell coordinate that the image is in the cell.
In the current stage, there are no methods for retrieving the images in Google Spreadsheet as the blob. In this sample script, this can be achieved.
This sample script cannot export the drawings. Please be careful this.
When setContentType(MimeType.ZIP) is not used, an error occurs at Utilities.unzip(blob). Please be careful this.
Pattern 2:
In this pattern, the images are retrieved with the sheet name and cell coordinate from Spreadsheet. In this case, the script becomes a bit complicated. So here, I would like to introduce the sample script using a Google Apps Script library. Ref Of course, you can see the whole script there.
Sample script:
Before you use this script, please install DocsServiceApp (The author of this GAS library is tanaike.) of the Google Apps Script library. Ref And run the function of myFunction.
function myFunction() {
const cell = "A1";
const sheetName = "Sheet1";
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const obj = DocsServiceApp.openBySpreadsheetId(spreadsheetId).getSheetByName(sheetName).getImages();
console.log(obj)
const blobs = obj.filter(({range, image}) => range.a1Notation == cell && image.innerCell);
console.log(blobs.length)
if (blobs.length > 0) DriveApp.createFile(blobs[0].image.blob);
}
In this sample, the image in the cell "A1" of "Sheet1" in the active Spreadsheet is retrieved, and the retrieved blob is created to the root folder as an image file.
Note:
In the current stage, when an image is inserted to Google Spreadsheet and the Spreadsheet is converted to XLSX data, the image including the XLSX data has the filename of image1, image2,,, which are not the original filename. So it seems that this is the current specification.
When the images are retrieved from XLSX data, it seems that the image is a bit different from the original one. The image format is the same. But the data size is smaller than that of the original. When the image size is more than 2048 pixels and 72 dpi, the image is modified to 2048 pixels and 72 dpi. Even when the image size is less than 2048 pixels and 72 dpi, the file size becomes smaller than that of original one. So I think that the image might be compressed. Please be careful this.
In the current stage, the drawings cannot be directly retrieved.
References:
Understanding the Open XML file formats
XML Service
DocsServiceApp
Now available as of January 2022 (release notes):
The following classes have been added to the Spreadsheet Service to let you add images to cells:
CellImageBuilder: This builder creates the image value needed to add an image to a >cell.
CellImage: Represents an image to add to a cell.
To add an image to a cell, you must create a new image value for the image using SpreadsheetApp.newCellImage() and CellImageBuilder. Then, use Range.setValue(value) or Range.setValues(values) to add the image value to the cell.
Example:
function insertImageIntoCell()
{
let image = SpreadsheetApp.newCellImage().setSourceUrl('https://www.gstatic.com/images/branding/product/2x/apps_script_48dp.png').setAltTextDescription('Google Apps Script logo').toBuilder().build();
SpreadsheetApp.getActive().getActiveSheet().getRange('A1').setValue(image);
}
Result:
function getImageFromCell()
{
let value = SpreadsheetApp.getActive().getActiveSheet().getRange('A1').getValue();
console.log(value.getAltTextDescription());
console.log(value.getUrl());
}
Result:
Note: getUrl returns null for this particular example, which seems to be due some internal API unavailability, from docs:
Gets the image's source URL; returns null if the URL is unavailable. If the image was inserted by URL using an API, this method returns the URL provided during image insertion.
This answer is about INSERTING in-cell images. I haven't been able to find a way to actually extract image data so Panos's answer is the best option for reading in-cell image data.
There are a few different ways to do this, some of them use some undocumented APIs.
1. =IMAGE(<http url>)
The =IMAGE is a standard function which displays in image within a cell. It does almost the exact same thing as manually inserting an in-cell image.
2. Copied-by-value =IMAGE
Once you have an =IMAGE image you can copy it and paste it by-value which will duplicate the image without the formula (if you want that for some reason). You can do this in a script using the copyTo function:
srcImageRange.copyTo(dstRange, { contentsOnly: true })
This formula-less IMAGE is only distinguishable from a true in-cell image in that when you right-click on it is missing the "Alt text" and "Put image over cells" context menu options. Those options only show up on real in-cell images.
3. The undocumented CellImage APIs
When you call getValue() on a in-cell image (both formula and manually inserted) you get a CellImage instance.
CellImage
Prop/method
(Return) Type
Description
toString()
string
returns "CellImage".
getContentUrl()
?
always throws an error?
toBuilder()
CellImageBuilder
Convert this into an writable CellImageBuilder instance.
getAltTextDescription()
string
Returns the alt text description.
getAltTextTitle()
string
Returns the alt text title.
getUrl()
?
Doesn't seem to work, always returns undefined. :(
valueType
?
Same as SpreadsheetApp.ValueType, doesn't seem meaningful.
CellImageBuilder
Has all the same properties and methods as CellImage with these additional ones:
Prop/method
(Return) Type
Description
toString()
string
returns "CellImageBuilder".
build()
CellImage
Convert into a (read-only) CellImage instance.
setSourceUrl(string)
void
Update the image by supplying a web or data URL.
setAltTextTitle(string)
void
Sets the alt text title.
setAltTextDescription(string)
void
Sets the alt text description.
The major benefit I see with using this over IMAGE() is that it supports data URLs and therefore indirectly supports blobs.
Working Example Code
Keep in mind the undocumented APIs might change without notice.
Link to Example Spreadhseet
// 1 (or just use IMAGE in formula directly)
function insertImageFormula(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
}
// 2
function insertImageValue(range, httpUrl) {
range.setFormula(`=IMAGE("${httpUrl}")`);
SpreadsheetApp.flush(); // Flush needed for image to load.
range.copyTo(range, { contentsOnly: true }); // Copy value onto itself, removing the formula.
}
// 3
function insertCellImage(range, sourceUrl) {
range.setFormula('=IMAGE("http")'); // Set blank image to get CellImageBuilder handle.
const builder = range.getValue().toBuilder();
builder.setSourceUrl(sourceUrl);
builder.setAltTextDescription(sourceUrl); // Put url in description for later identification, for example.
range.setValue(builder.build());
}
const DATA_URI = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7///"
+ "/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAos"
+ "J6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
function test() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.clear();
sheet.getRange(1, 1).setValue("IMAGE formula");
insertImageFormula(sheet.getRange(2, 1), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 2).setValue("Copied-by-value IMAGE");
insertImageValue(sheet.getRange(2, 2), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 3).setValue("In-Cell Image (Http URL)");
insertCellImage(sheet.getRange(2, 3), "https://www.google.com/images/icons/illustrations/paper_pencil-y128.png");
sheet.getRange(1, 4).setValue("In-Cell Image (DATA URI)");
insertCellImage(sheet.getRange(2, 4), DATA_URI);
sheet.getRange(1, 5).setValue("In-Cell Image (Blob DATA URI)");
const blob = UrlFetchApp.fetch("https://www.gstatic.com/script/apps_script_1x_24dp.png").getBlob();
insertCellImage(sheet.getRange(2, 5), blobToDataUrl(blob));
}
function blobToDataUrl(blob) {
return `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`
}
Both Rafa Guillermo and Tanaike requested that I make an answer based on my comment to Tanaike’s post. I do so below, but it falls into the category of a workaround rather than an "answer". A true answer would address the exact question in the original post.
As I said in my comment, I’ve used this method for simple cases, and I’ve also done some tests which suggest it preserves image resolution. Since I've only used this for simple cases like the one below, I don't know how generally it will work.
The steps I provide below are (to the best of my ability) what I remember going through as I did one specific example. Here are the first dozen rows of the final result after using this method:
This example had a total of 7100+ rows
Column 1 contained 430+ images or blank cells, most of which repeated
multiple times
Column 2 contained unique IDs for each image
Column 3 are the file names which were tied to each ID using the
method below
Steps to extract images from google sheet cells:
Resize column and rows containing images to something large (eg, 300)
Use File>Publish to Web & paste generated link into a new tab
In Chrome, use File>Save Page As…>Webpage, Complete
Images will be found in an html folder ending with _files
If needed, rename files to use image extension and list in order*
To key downloaded image file names to image cells in the sheet:
Duplicate sheet since the following will remove original data
Select columns containing images and IDs and use Data>Remove Duplicates
Add a new column next to the IDs containing the file names**
Use VLOOKUP function to transfer all file names to original sheet based on the unique IDs***
*In my example the images all had names like p.txt, p(1).txt, p(2).txt, etc… In Mac OS Finder, I selected all files and used right click>Rename files… and then the replace option to replace .txt with .jpg, (1) with (001), etc…
**file name listing can be obtained, for example, using the Terminal ls -l command
***for example, I used: =vlookup(B2,unique!$B$2:$C$430,2,false)
This question is a little old, but since I faced today this problem, please allow me to share my experience.
I realized that the getValue() of the cell, returns an object that its text is "CellImage". This allows me to understand that there is an embedded image in this cell. This objects seems to be similar to (or the same) with the OverGridImage object. At least, you can use the getAltTextTitle and the getAltTextDescription methods.
By combining all these features, my workaround is:
Add specific AltText to the image in the cell.
Get the value of the cell in an object.
Check if this is equals to "CellImage".
If it is CellImage, get the AltText.
Based on the value of this AltText do whatever you like.
The sample code follows:
/*-------------------------------------------------------------------------
Custom event handler triggered when a single cell is selected in the spreadsheet.
#param {Event} e The onSelectionChange event.
-------------------------------------------------------------------------*/
function onSingleCellSelected(e) {
var cell = e.range.getCell(1, 1);
var v = cell.getValue();
if(v == "CellImage") {
var altText = v.getAltTextTitle();
Logger.log(v.getAltTextDescription());
if(altText == "#action(recordTime)"){
cell.setBackground("cyan");
}
}
}
I just tried something pretty basic and it worked. Maybe doesn't work in all cases, depends if you added the images previously through a formula...
Add image through Google Apps Script :
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
sheet.getRange('A1').setFormula('=IMAGE("https://developers.google.com/google-ads/scripts/images/reports.png")');
Worked (it's in the cell and will work auto fit on resizing) :
Then to retrieve the image url from cell :
var imgVal = sheet.getRange('A1').getFormula();
var regEx = /"(.*)"/gm;
var url = regEx.exec(imgVal)[1];
Logger.log(url);
Logs will be :
I am trying to get the following table - from link - into a google sheet.
I tried the following:
=IMPORTXML("http://www.immopreise.at/Wien/Wohnung/Miete","//table[#id='preisTabelle']")
Attached you can find an example sheet:
https://docs.google.com/spreadsheets/d/1-aXJULo6BELQQ6136Lps_HUzOwkw5SKaPGxIl5gBDfM/edit?usp=sharing
My problem is I do not get anything back.
Any suggestions what I am doing wrong?
I appreciate your reply!
First Approach: Here is how you can do it (Using ImportXml and RegexExtract:
=IMPORTXML("http://www.immopreise.at/Wien/Wohnung/Miete",
"//table[#id='preisTabelle']")
The mentioned code produces an empty string, because, the web page has an empty table at that location, shown as below:
<table id="preisTabelle"></table>
The data is actually located inside a <script> tag:
<script>
var ImmoOptions = {"mapOptions":{"region":"Wien","karteAnzeigen":true},"TrendChartConf":{"uri":{"district":"/Trend/GetDistricts","chart":"/Trend/GetChart","chart1":"/Trend/GetTrendChart","compare":"/Preisvergleich","chart2":"/Trend/TrendChart","refresh":"/Preisentwicklung","uebersicht":"/?region=Wien\u0026pathInfo=Wohnung%2FMiete"},"firstDirstrict":{"Wien":"Wien-1-Innere-Stadt","Niederoesterreich":"Sankt-Poelten-Stadt","Burgenland":"Eisenstadt-Stadt","Oberoesterreich":"Linz-Stadt","Steiermark":"Graz-Alle-Bezirke","Kaernten":"Klagenfurt-Stadt","Salzburg":"Salzburg-Stadt","Tirol":"Innsbruck-Stadt","Vorarlberg":"Bregenz"},"firstDirstrictId":{"9":231,"3":153,"1":133,"4":177,"6":201,"2":142,"5":195,"7":218,"8":228}},"preisInfos":{"tabelle":{"spalten":[{"name":"≤50m²","spaltenArt":"Waehrung","nachkommaStellen":true,"farbmarkierung":null},{"name":"51-80m²","spaltenArt":"Waehrung","nachkommaStellen":true,"farbmarkierung":null},{"name":"81-129m²","spaltenArt":"Waehrung","nachkommaStellen":true,"farbmarkierung":null},{"name":"\u003e130m²","spaltenArt":"Waehrung","nachkommaStellen":true,"farbmarkierung":null},{"name":"\u003cspan class=\u0027Detailed\u0027\u003e\u0026#216;/m²\u003c/span\u003e\u003cspan class=\u0027Compact\u0027\u003e\u0026#216;/m²\u003c/span\u003e","spaltenArt":"Waehrung","nachkommaStellen":true,"farbmarkierung":true},{"name":"\u003cspan class=\u0027Detailed\u0027\u003eTrend\u003c/span\u003e\u003cspan class=\u0027Compact\u0027\u003eTd.\u003c/span\u003e","spaltenArt":"Tendenz","nachkommaStellen":false,"farbmarkierung":null}],"zeilen":[{"name":" 1., Innere Stadt","zellen":[21.68,19.02,18.43,19.56,19.27,0],"id":231},{"name":" 2., Leopoldstadt","zellen":[18.27,15.06,14.28,14.20,14.85,1],"id":232},{"name":" 3., Landstraße","zellen":[18.88,17.04,15.42,14.68,16.03,1],"id":233},{"name":" 4., Wieden","zellen":[19.37,16.58,16.89,16.35,16.83,1],"id":234},{"name":" 5., Margareten","zellen":[15.46,14.11,14.20,14.77,14.39,0],"id":235},{"name":" 6., Mariahilf","zellen":[18.23,14.68,15.72,15.32,15.53,1],"id":236},{"name":" 7., Neubau","zellen":[16.09,14.89,14.58,14.94,14.95,0],"id":237},{"name":" 8., Josefstadt","zellen":[16.77,16.78,14.02,14.93,15.08,0],"id":238},{"name":" 9., Alsergrund","zellen":[15.72,14.48,14.53,14.92,14.69,0],"id":239},{"name":"10., Favoriten","zellen":[14.14,12.35,11.81,0,12.52,0],"id":240},{"name":"11., Simmering","zellen":[13.69,12.34,11.50,13.46,12.38,-1],"id":241},{"name":"12., Meidling","zellen":[15.66,14.97,13.28,11.79,14.54,1],"id":242},{"name":"13., Hietzing","zellen":[16.71,15.93,14.63,14.05,14.99,0],"id":243},{"name":"14., Penzing","zellen":[14.43,13.14,12.72,12.37,13.11,0],"id":244},{"name":"15., Rudolfsheim-Fünfhaus","zellen":[13.58,12.90,12.93,11.76,13.07,0],"id":245},{"name":"16., Ottakring","zellen":[13.99,12.64,12.64,12.45,12.90,0],"id":246},{"name":"17., Hernals","zellen":[14.71,13.06,13.15,13.61,13.50,1],"id":247},{"name":"18., Währing","zellen":[14.47,13.96,13.82,15.67,14.37,0],"id":248},{"name":"19., Döbling","zellen":[16.21,14.37,15.06,16.44,15.29,0],"id":249},{"name":"20., Brigittenau","zellen":[15.68,13.57,12.56,13.30,13.43,0],"id":250},{"name":"21., Floridsdorf","zellen":[15.58,13.58,12.38,14.97,13.68,1],"id":251},{"name":"22., Donaustadt","zellen":[18.19,15.57,16.85,15.89,16.18,0],"id":252},{"name":"23., Liesing","zellen":[14.79,14.09,13.49,15.60,13.92,1],"id":253}],"tabellenTitel":"Wohnungen Miete","titelErsteSpalte":"Bezirk","GesamtAnzahlObjekte":12739},"preisspannen":[{"bis":12},{"bis":14},{"bis":15},{"bis":null}]},"basecharts":null,"CurrentView":{"trendVar":{"CatNum":0,"ImmoArtNum":5,"AltbauNum":2,"AngebotTypeNum":1},"hid":0}} ;
jQuery(function () {
InitMap(ImmoOptions.mapOptions);
});
</script>
The data of most interest is found inside variable ImmoOptions:
[
{
"name": " 1., Innere Stadt",
"zellen": [21.68, 19.02, 18.43, 19.56, 19.27, 0],
"id": 231
},
{
"name": " 2., Leopoldstadt",
"zellen": [18.27, 15.06, 14.28, 14.2, 14.85, 1],
"id": 232
},
/* Edited for brevity */
]
The following formula can get the script into a cell in spread sheet (let's say we pasted it into cell A[100]) ..
=IMPORTXML("http://www.immopreise.at/Wien/Wohnung/Miete","//script[2]")
Then, the following formula extracts JSON string (value of the ImmoOptions variable) into a cell (let's say we pasted the following into cell A[1]) ..
=REGEXEXTRACT(A100,"(?s)=(.*)")
At this point, we need javascript to parse JSON. This can be done by converting the sheet to a Google App (Tools->Script Editor) and doing the coding in javascript.
In the javascript, there will be three steps (The details are not shown here):
1. Use IMPORTXML to get the data inside script (in the url/page)
2. Use REGEXEXTRACT to get the value of ImmoOptions as JSON string
3. Parse JSON string to get the data
Second Approach: Here is how you can do it using Google App/Script:
Log into google and open this spreadsheet in browser.
Choose File->Make a Copy (may be with a name like S1). This will make a copy of the file in your google drive; and opens it in a new tab.
Go to that new window/tab. Choose Tools->Script Editor. This will put you into a editor with the script. From the toolbar select the function doGet and run the script; it will generate the spreadsheet.
Here is the script attached with the sheet (for reference, in case the link goes missing):
function doGet() {
var r1=Math.random()*100000000000;
var html = UrlFetchApp.fetch("http://www.immopreise.at/Wien/Wohnung/Miete?somevariable=" + r1).getContentText();
var re = /var ImmoOptions = (.*);/i;
var jo=JSON.parse(re.exec(html)[1]);
var arr=jo["preisInfos"]["tabelle"]["zeilen"];
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear(); sheet.appendRow([r1]);
sheet.appendRow(['Bezirk','Col-1','Col-2','Col-3','Col-4','Col-5','Col-6']);
for (var i=0;i<arr.length;i++) {
var item = arr[i]; var row=[item.name];
row=row.concat(item.zellen); sheet.appendRow(row);
}
}
How it works:
Pulls the entire html content of the relevant url.
Uses regular expression to extract json data from inside <script>..</script>
Parses the extracted json data.
Gets the relevant array; populates into the spreadsheet.
Disadvantages:
It is a brittle patch-work script that will break with changes in the <script> include (or in any other way regex's break)
Doesn't give you nice controls on the UI of table (They could be built, but with more work).
Works only if the entire json data is in a single line (Could be modified by removing new lines .. or by using a proper regex).
I am trying to figure out how to use conditional formatting on a google spreadsheet similar to what you can do in excel via a formula.
I want cell A2 to change to Green if cell O2 has a value of "X" and this will be done on both columns all the way down. I know this will require a script.
I ran across a link that is similar but i do not know how to adjust it to meet my needs. Is this something that can be done?
Link: https://webapps.stackexchange.com/questions/16745/google-spreadsheets-conditional-formatting
Here's a script you could use to do what you described:
function formatting() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var columnO = sheet.getRange(2, 15, sheet.getLastRow()-1, 1);
var oValues = columnO.getValues();
for (var i = 0; i < oValues.length; i++) {
if (oValues[i][0] == 'X') {
sheet.getRange(i + 2, 1, 1, 1).setBackgroundColor('green');
}
}
}
In the new Google sheets, this no longer requires a script.
Instead, in conditional formatting, select the option "custom formula", and put in a value like =O2="X" - or indeed any expression that returns a boolean true/false value.
From what I can tell, the references listed in these custom scripts are a bit weird, and are applied as follows...
If it's a cell within your selected range, then it is changed to "the cell that's being highlighted".
If it's a cell outside your selected range, then it's changed to "that position, plus an offset the same as the offset from the current cell to the top left of the selected range".
That is, if your range was A1:B2, then the above would be the same as setting individual formatting on each cell as follows:
A1 =O2="X"
A2 =O3="X"
B1 =P2="X"
B2 =P3="X"
You can also specify fixed references, like =$O$2="X" - which will check the specific cell O2 for all cells in your selected range.
(Feb 2017) As mentioned in another answer, Google Sheets now allows users to add Conditional Formatting directly from the user interface, whether it's on a desktop/laptop, Android or iOS devices.
Similarly, with the Google Sheets API v4 (and newer), developers can now write applications that CRUD conditional formatting rules. Check out the guide and samples pages for more details as well as the reference docs (search for {add,update,delete}ConditionalFormatRule). The guide features this Python snippet (assuming a file ID of SHEET_ID and SHEETS as the API service endpoint):
myRange = {
'sheetId': 0,
'startRowIndex': 1,
'endRowIndex': 11,
'startColumnIndex': 0,
'endColumnIndex': 4,
}
reqs = [
{'addConditionalFormatRule': {
'index': 0,
'rule': {
'ranges': [ myRange ],
'booleanRule': {
'format': {'textFormat': {'foregroundColor': {'red': 0.8}}}
'condition': {
'type': 'CUSTOM_FORMULA',
'values':
[{'userEnteredValue': '=GT($D2,median($D$2:$D$11))'}]
},
},
},
}},
{'addConditionalFormatRule': {
'index': 0,
'rule': {
'ranges': [ myRange ],
'booleanRule': {
'format': {
'backgroundColor': {'red': 1, 'green': 0.4, 'blue': 0.4}
},
'condition': {
'type': 'CUSTOM_FORMULA',
'values':
[{'userEnteredValue': '=LT($D2,median($D$2:$D$11))'}]
},
},
},
}},
]
SHEETS.spreadsheets().batchUpdate(spreadsheetId=SHEET_ID,
body={'requests': reqs}).execute()
In addition to Python, Google APIs support a variety of languages, so you have options. Anyway, that code sample formats a Sheet (see image below) such that those younger than the median age are highlighted in light red while those over the median have their data colored in red font.
PUBLIC SERVICE ANNOUNCEMENT
The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (conditional formatting[!], frozen rows, cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.).
If you're new to the API & want to see slightly longer, more general "real-world" examples of using the API, I've created various videos & related blog posts:
Migrating SQL data to a Sheet plus code deep dive post
Formatting text using the Sheets API plus code deep dive post
Generating slides from spreadsheet data plus code deep dive post
As you can tell, the Sheets API is primarily for document-oriented functionality as described above, but to perform file-level access such as uploads & downloads, imports & exports (same as uploads & downloads but conversion to/from various formats), use the Google Drive API instead. Examples of using the Drive API:
Exporting a Google Sheet as CSV (blog post only)
"Poor man's plain text to PDF" converter (blog post only) (*)
(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a video combining both "poor man's converter" posts.
With the latest Sheet API you can programmatically add a conditional formatting rule to your sheet to do the highlighting.
You can add a custom formula rule that will set the background colour to green in column A where column O is "X" like this:
function applyConditionalFormatting() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var numRows = sheet.getLastRow();
var rangeToHighlight = sheet.getRange("A2:A" + numRows);
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied('=INDIRECT("R[0]C[14]", FALSE)="X"')
.setBackground("green")
.setRanges([rangeToHighlight])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
The range that the conditional formatting applies to is the A column from row 2 to the last row in the sheet.
The custom formula is:
=INDIRECT("R[0]C[14]", FALSE)="X"
which means go 14 columns to the right of the selected range column and check if its value is "X".
Column O is 14 columns to the right of column A.