使用代码将 GOOGLE APPS 脚本功能分配给图像。
通过单击 Google 表格中的图像并选择“分配脚本”选项,就可以实现这一点。
但这是一项手动任务,我想将其自动化。
可以将图像插入 Google 表格并使用 Apps 脚本代码分配函数。
有一个insertImage()
Sheet 类的方法和assignScript()
可以在图像上运行的方法。
The 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'});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)