如何在 Gsheet 单元格上显示来自 Google Drive 的图像?

Moh*_*d H 7 google-sheets google-apps-script google-sheets-formula

我想根据存储在 Gdrive 中的图像的 URL 在 Gsheet 单元格上轻松显示图像。

我尝试过使用 Gsheet 函数 =IMAGE("URL") 但它不起作用。

目的是显示一个图像图片,如下例所示(第5行图片的示例是手动完成的)

显示图像示例

Tan*_*ike 12

  • 您想将 Google 云端硬盘中的图像放入 Google 电子表格中。
  • 您希望使用 Google Apps 脚本来实现此目的。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

模式一:

在此模式中,使用 放置图像=IMAGE("URL")

使用时=IMAGE("URL"),需要将图片公开共享。因此,请将图像公开共享为On - Anyone with the link

另外,请按如下方式修改端点。

从:

https://drive.google.com/open?id=###
Run Code Online (Sandbox Code Playgroud)

到:

https://drive.google.com/uc?export=download&id=###
Run Code Online (Sandbox Code Playgroud)
  • =IMAGE("https://drive.google.com/uc?export=download&id=###")在这种情况下,您可以在图像公开共享后将图像添加到。

模式2:

如果您不想公开分享图像,那么这种模式怎么样?在此模式中,图像作为 blob 放置,而不公开共享。

在这里,请检查以下示例脚本。

示例脚本:

var fileId = "###";  // Please set the file ID of the image.

var sheet = SpreadsheetApp.getActiveSheet();
var blobSource = DriveApp.getFileById(fileId).getBlob();
var image = sheet.insertImage(blobSource, 1, 1);
image.setWidth(100).setHeight(100);
sheet.setColumnWidth(1, 100).setRowHeight(1, 100);
Run Code Online (Sandbox Code Playgroud)
  • 运行脚本时,图像将被放入单元格“A1”中。并且图像大小被调整为 100 x 100 像素。然后,行和列的大小根据图像大小进行更改。
  • 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。

参考:

如果我误解了你的问题并且这不是你想要的方向,我很抱歉。

添加:

从您的回复中发现图片尺寸超过了限制尺寸(1,048,576 pixels^2Ref您当前的原因是这样的。

在这种情况下,为了放置图像,需要调整图像的大小。以下示例脚本通过调整图像大小来放置图像。为此,我使用了 Google Apps 脚本库。因此请将其安装到脚本编辑器中

示例脚本:

var fileId = "###";  // Please set the file ID of the image.

var sheet = SpreadsheetApp.getActiveSheet();
var blobSource = DriveApp.getFileById(fileId).getBlob();
var obj = ImgApp.getSize(blobSource);
var height = obj.height;
var width = obj.width;
if (height * width > 1048576) {
  var r = ImgApp.doResize(fileId, 512);
  blobSource = r.blob;
}
var image = sheet.insertImage(blobSource, 1, 1);
image.setWidth(100).setHeight(100);
sheet.setColumnWidth(1, 100).setRowHeight(1, 100);
Run Code Online (Sandbox Code Playgroud)
  • 在此示例脚本中,当图像大小超过 时1,048,576 pixels^2,将调整图像大小并将其放入电子表格中。
  • 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。

参考:

更新日期:2023 年 9 月 30 日

作为目前的方法,我认为也可以使用以下模式。

脚本1:

在此脚本中,从 Google Drive 检索的文件内容用作 SpreadsheetApp.CellImage 的对象。在这种情况下,当图像尺寸较大时,可能会出现错误。请注意这一点。

https://drive.google.com/open?id=###
Run Code Online (Sandbox Code Playgroud)

运行此脚本时,图像将被放入单元格“A1”中。

脚本2:

在此脚本中,将从 Google Drive 检索到的文件内容的缩略图用作 SpreadsheetApp.CellImage 的对象。在这种情况下,即使图像尺寸很大,也可以使用该脚本,因为图像尺寸会被调整。

https://drive.google.com/uc?export=download&id=###
Run Code Online (Sandbox Code Playgroud)

运行此脚本时,图像将被放入单元格“A1”中。

参考: