Image 将Google应用程序脚本函数分配给带有代码的Google Sheets图像
为带有代码的图像分配GOOGLE应用程序脚本函数 通过点击谷歌工作表中的图像并选择“分配脚本”选项,这是可能的Image 将Google应用程序脚本函数分配给带有代码的Google Sheets图像,image,button,google-apps-script,google-sheets,Image,Button,Google Apps Script,Google Sheets,为带有代码的图像分配GOOGLE应用程序脚本函数 通过点击谷歌工作表中的图像并选择“分配脚本”选项,这是可能的 但这是一项手动任务,我想将其自动化。可以将图像插入谷歌工作表,并使用应用程序脚本代码分配一个功能 Sheet类有一个insertImage()方法和一个可以在图像上运行的assignScript()方法 insertImage()方法需要图像mime类型的blob。要获取jpeg mime类型的图像,您可以绘制图像并将其保存到本地驱动器,将图像上载到Google驱动器,然后使用代码将
但这是一项手动任务,我想将其自动化。可以将图像插入谷歌工作表,并使用应用程序脚本代码分配一个功能 Sheet类有一个
insertImage()
方法和一个可以在图像上运行的assignScript()
方法
insertImage()
方法需要图像mime类型的blob。要获取jpeg mime类型的图像,您可以绘制图像并将其保存到本地驱动器,将图像上载到Google驱动器,然后使用代码将图像作为blob获取
创建图像、将其作为blob获取、插入工作表和指定函数的步骤
- 在Google工作表中,单击“插入”,然后单击“绘图”
- 绘制图像-例如,看起来像按钮的图像
- 将图像保存到计算机驱动器
- 在Google Drive中,单击“新建”和“文件上载”,然后将图像文件上载到您的Google Drive并为其命名
- 获取代码中的图像文件,如下面的测试函数所示
- 将图像文件转换为代码中的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'});
}
不确定你到底在寻找什么-你看过项目触发器了吗?这可以自动化任务。如果图像被放置在html服务生成的边栏或对话框上,那么您可以为它们分配onClick事件,并于2018年10月30日发布了一项新功能。请参见,现在允许使用代码将脚本分配给图像。见新答案。