【问题标题】:Assign a Google Apps Script function to a Google Sheets image with code使用代码将 Google Apps 脚本函数分配给 Google 表格图像
【发布时间】:2017-04-05 10:52:14
【问题描述】:

将 GOOGLE 应用程序脚本功能分配给带有代码的图像。

通过单击 Google 表格中的图像并选择“分配脚本”选项,这是可能的。

但这是一项手动任务,我想将其自动化。

【问题讨论】:

  • 不确定您正在寻找的究竟是什么 - 您查看过项目触发器吗?这可以自动执行任务。
  • 如果图像放置在使用 html 服务生成的侧边栏或对话框上,那么您可以将 onClick 事件分配给它们和run any server side google apps script
  • 2018 年 10 月 30 日发布了一项新功能。请参阅 release notes,该功能现在允许将脚本分配给带有代码的图像。查看新答案。

标签: image button google-apps-script google-sheets


【解决方案1】:

可以将图像插入 Google 表格并使用 Apps 脚本代码分配功能。

Sheet 类有一个insertImage() 方法和一个可以在图像上运行的assignScript() 方法。

insertImage() 方法需要图像 mime 类型的 blob。要获取 jpeg mime 类型的图像,您可以绘制和图像,将其保存到本地驱动器,将图像上传到您的 Google 驱动器,然后使用代码将图像作为 blob 获取。

创建图像、将其作为 blob 获取、插入工作表并分配功能的步骤

  • 在 Google 表格中点击“插入”,然后点击“绘图”
  • 绘制图像 - 例如看起来像按钮的图像
  • 将图像保存到您的计算机驱动器
  • 在 Google 云端硬盘中,点击“新建”和“文件上传”,然后将图片文件上传到您的 Google 云端硬盘并为其命名
  • 代码中获取图片文件如下测试函数所示
  • 在代码中将图像文件转换为 blob
  • 运行代码以插入图像并分配函数

代码示例:

请注意,在带有电子表格的浏览器选项卡被刷新之后,图像才会显示。

function setImage(po) {
try{
  var image,sh,ss;

  /*
    po.blobSource - a blob that is an image file type
    po.column - the column to set the image in
    po.functionName - the name of the function to assign to the image
    po.row - the row to set the image in
    po.shName - the name of the sheet tab
  */

  ss = SpreadsheetApp.getActiveSpreadsheet();//This code is bound to a Sheet
  sh = ss.getSheetByName(po.shName);
  image = sh.insertImage(po.blobSource, po.column, po.row);//Insert an image and return the image

  image.assignScript(po.functionName);//Assign an Apps Script function to the image

  return true;
}catch(e){
  //Logger.log('Error: ' + e.message)
  //Logger.log('stack: ' + e.stack)
  return false;
}
}

function testRun() {
  var blobSrc,contentType,file,files;

  /*
    In a Sheet click Insert and Drawing
    Draw a button
    Save the button to your computer drive
    From Google Drive click "New" and File Upload and upload the file and give it a name
    Get the image file in code as shown in this function
    Convert the image file to a blob
  */

  files = DriveApp.searchFiles('mimeType contains "jpeg" and title contains "Name of File Here"');
  if (files.hasNext()) {
   file = files.next();
  }

  contentType = 'image/jpeg';

  if (file) {
    blobSrc = file.getAs(contentType);
  }

  //Logger.log(blobSrc.getContentType());  

  //Logger.log(blobSrc.getName())
  setImage({shName:'Sheet1',blobSource:blobSrc,row:1,column:1,functionName:'myFunction'});

}

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2022-09-25
    • 1970-01-01
    相关资源
    最近更新 更多