【问题标题】:How can I return an image as the output of a google sheet custom function?如何返回图像作为 google sheet 自定义函数的输出?
【发布时间】:2021-02-23 19:42:21
【问题描述】:

我在谷歌表格中有一个自定义函数。如何返回图像而不是普通数据(例如数字)作为此自定义函数的输出?

事实上,我打算从 image-charts.com 网站读取这张图片,这意味着 image-charts.com 为我们创建了这张图片并给了我们它的 url,我实际上希望能够使用这张图片是在 Google 表格单元格中创建的。

google sheet 自定义函数能否支持图片作为函数的返回值?

提前致谢

【问题讨论】:

  • 您能否提供更多有关您如何提出请求的信息?它是通过按钮调用函数吗?触发器?在公式中调用函数?根据您在哪里执行此操作,您将拥有不同的权限,并且可能/可能无法添加图像。
  • 当然,没有按钮也没有触发器。它只是一个在公式中调用的函数。该脚本被执行,该脚本的输出是一个图像的链接(即该链接包含一个图像),我想在单元格内显示该图像。

标签: google-sheets custom-function


【解决方案1】:

更新

找到了您真正想要的答案。有 IMAGE (see reference),一个将 URL 作为图像添加到单元格中的函数(不知道它存在)。所以你可以这样做:

=IMAGE(GETCHARTURL(...))

原始解决方法

您不能在单元格中添加图像。您也不能将图像显示为公式的结果。 最好的你可以做的是有一个按钮,调用一个谷歌应用程序脚本函数,使用Sheet.insertImagereference)将图像添加到单元格顶部。

我制作了这个小脚本,它会自动将图像添加到具有值 img+ 的单元格顶部,后跟图像 URL(例如 img+https://example.com/image.png):

const IMAGE_HEIGHT = 100 // Image height in pixels
function sameRange(a, b) {
  return a.getGridId() === b.getGridId()
    && a.getA1Notation() === b.getA1Notation()
}
function addImages() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet()
  const toChange = sheet
    .createTextFinder(/^img\+https?:\/\//.source)
    .useRegularExpression(true)
    .findAll()

  // Remove old image(s)
  for (let img of sheet.getImages()) {
    const range = img.getAnchorCell()
    if (toChange.some(r => sameRange(r, range))) {
      img.remove()
    }
  }

  // Create new ones
  for (let range of toChange) {
    const url = range.getValue().toString().split(/\+(.*)$/, 2)[1]
    const image = range.getSheet()
      .insertImage(url, range.getColumn(), range.getRow(), 0, 0)
    
    image.setAltTextTitle("Chart")

    const w = image.getWidth()
    const h = image.getHeight()
    image.setWidth(IMAGE_HEIGHT*w/h) // Keep aspect ratio
    image.setHeight(IMAGE_HEIGHT)
  }
}

然后只需制作一个新按钮(带有文本的绘图)并将addImages 设置为分配的脚本。

我不知道您的确切用例,因此您可能需要修改脚本以更好地满足您的需求。

参考文献

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 2021-10-04
    • 2013-12-21
    • 2018-11-17
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多