I was using this script below to insert images from a URL into specified cells in Google Sheets, however, it won\'t work for image URLs contained within Google Drive.
IMAGE()
.
https://google.com/image.png
and https://drive.google.com/open?id=###
.https://google.com/image.png
is the external link.https://drive.google.com/open?id=###
is the link in your Google Drive.If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Unfortunately, the image files in the Google Drive cannot be directly put to the Spreadsheet using IMAGE()
. In this case, the image files are required to be publicly shared. So in this answer, the files are publicly shared and put to the Spreadsheet.
When your script is modified, please modify as follows.
From:for (var num = 0; num < source.length; num ++) {
if (/https?:\/\//.test(source[num][0])) { //Check to ensure a URL has been entered.
var graphicformula = '=IMAGE("' + source[num][0] + '",1)';
dstSheet.getRange(graphics_placements[num]).setFormula(graphicformula);
}
}
To:
for (var num = 0; num < source.length; num ++) {
if (/https?:\/\//.test(source[num][0])) { //Check to ensure a URL has been entered.
var res = source[num][0].match(/drive\.google\.com\/open\?id=(\w.+)|drive\.google\.com\/file\/d\/(\w.+)\//);
if (res && res.length > 0) {
var id = res[1] || res[2];
var file = DriveApp.getFileById(id);
if (file.getOwner().getEmail() != Session.getActiveUser().getEmail()) {
file = file.makeCopy(DriveApp.getRootFolder());
}
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
source[num][0] = "https://drive.google.com/uc?export=download&id=" + id;
}
var graphicformula = '=IMAGE("' + source[num][0] + '",1)';
dstSheet.getRange(dstSheet.getLastRow() + 1, 1).setFormula(graphicformula);
}
}
DriveApp.getRootFolder()
.https://drive.google.com/open?id=###
are included, please show the sample URLs.Please modify the for loop in your script as follows.
var scale = 0.5; // In this case, the imported image is reduces with 50 % from the original size.
var n = 0;
var cellWidth = 0;
for (var num = 0; num < source.length; num ++) {
if (/https?:\/\//.test(source[num][0])) { //Check to ensure a URL has been entered.
var res = source[num][0].match(/drive\.google\.com\/open\?id=(\w.+)|drive\.google\.com\/file\/d\/(\w.+)\//);
var blob = res && res.length > 0 ? DriveApp.getFileById(res[1] || res[2]).getBlob() : UrlFetchApp.fetch(source[num][0]).getBlob();
var lastRow = dstSheet.getLastRow() + 1 + n++;
var image = dstSheet.insertImage(blob, 1, lastRow);
var imageWidth = image.getWidth() * scale;
var imageHeight = image.getHeight() * scale;
cellWidth = cellWidth > imageWidth ? cellWidth : imageWidth;
image.setWidth(imageWidth);
image.setHeight(imageHeight);
dstSheet.setRowHeight(lastRow, imageHeight);
}
}
dstSheet.setColumnWidth(1, cellWidth);
dstSheet.setRowHeight(lastRow, imageHeight)
and dstSheet.setColumnWidth(1, cellWidth)
change the cell size.