Insert an image into a cell in Google Sheets using Apps Script

In this tutorial, I will show you how to insert an image into a cell in a Google Sheets spreadsheet using Apps Script.

What is a cell image?

A cell image is simply an image that is inserted into a cell. It has been possible to insert images into cells in Google Sheets using the =IMAGE() function in Google Sheets for some time. However, this wasn't possible using Apps Script up until recently.

For example, let's say we want to insert the following image into cell A1 in the active sheet.

Image credit: Abhijit Tembhekar from Mumbai, India, CC BY 2.0, via Wikimedia Commons

Previously, the only way to insert this image into cell A1 would be using a formula and the =IMAGE() function.

=IMAGE("https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/128px-Red_Apple.jpg")

Insert an image into a cell in Google Sheets using Apps Script

Now, you can also insert images into cells using Apps Script. The function insertCellImage() below does just that. It accepts a range and the url of the image and inserts the image into all the cells in that range. You can also optionally supply an alternate title and description for the image to help improve the accessibility of content in your spreadsheet.

function insertCellImage(range, imageUrl, altTitle = "", altDescription = "") {

 let image = SpreadsheetApp
                 .newCellImage()
                 .setSourceUrl(imageUrl)
                 .setAltTextTitle(altTitle)
                 .setAltTextDescription(altDescription)
                 .build();
  range.setValue(image);

}

Reading cell images from a Google Sheets spreadsheet using Apps Script

Now that you can insert images into cells, you might encounter images while reading values from a range in your spreadsheet using Apps Script.

In the above example, we inserted the image of the apple into cell A1. Now, suppose that cell is the current cell (i.e. the cell that is active in the spreadsheet). You can get its value using SpreadsheetApp.getCurrentCell().getValue(). This value will be an image. The function getCellImage() below shows you how to find out if a value is a cell image or not.

function getCellImage(cell) {
  let val = cell.getValue();
  
  //Check if the value in the cell is an image.
  if(val.toString() === "CellImage") {
    Logger.log(val.getUrl());
    Logger.log(val.getAltTextTitle());
    Logger.log(val.getAltTextDescription());
  }
}

Conclusion

You learned how to insert images into cells in Google Sheets using Apps Script. Hope this tutorial was helpful. Thanks for reading!

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.