google-sheets - 如何检查 IMAGE 公式中使用的 url 是否正确并显示图像?
问题描述
我有一个使用文件名引用的图像列表:
=image("domainname.com/somepath/"&A2&".jpg")
其中 A2 是文件名。
不幸的是,其中一些图像具有 .png 扩展名。我试图找到一个解决方案来检查带有 jpg 扩展名的文件是否正确并找到图像。如果没有找到我想使用
=image("domainname.com/somepath/"&a2&".png")
对于这个细胞。
IFNA 和 IFERROR 公式不起作用。我还尝试连接公式:
=image("domainname.com/somepath/"&a2&".png")&image("domainname.com/somepath/"&a2&".jpg")
但我看到您只能将 & 用于字符串
不同文件夹中有数千张图片供参考,我无法控制它们的格式。你有什么主意吗?
解决方案
我建议的一种解决方法是创建并使用自定义函数来验证图像 URL。
- Google 表格提供了数百种内置函数,例如 AVERAGE、SUM 和 VLOOKUP。当这些不足以满足您的需求时,您可以使用 Google Apps 脚本编写自定义函数(例如,将米转换为英里或从 Internet 获取实时内容)然后在 Google 表格中使用它们,就像内置函数一样。
示例自定义函数:
/**
* validate image
*
* @param {input} image url to validate.
*
* @customfunction
*/
function IMAGE_TRY(input) {
try{
var response = UrlFetchApp.fetch(input);
return 1;
} catch(err) {
return 0;
}
}
- 此自定义函数将采用 1 个图像 URL 参数并使用 try-catch 方法验证该 URL 是否有效。该函数将在 URL 有效时返回 1,如果不是有效 URL,则返回 0
请注意,@customfunction 标记在函数注释中很重要,因此当您在单元格中键入时,此自定义函数将显示为建议的公式。
创建自定义函数后,您可以使用它来验证 URL 并使用 IF 函数使用正确的图像 URL。
样本:
=IF(IMAGE_TRY("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.jpg"),image("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.jpg"), image("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.png"))
样本输出:
(更新)
优化解决方案:
示例自定义函数:
/**
* get image url with correct file extension.
*
* @param {input} image url string without extension.
*
* @customfunction
*/
function getURL(input) {
try{
var response = UrlFetchApp.fetch(input+".jpg");
return (input.concat(".jpg"));
} catch(err) {
return (input.concat(".png"));
}
}
- 此解决方案接受没有文件扩展名的图像 URL,并返回具有有效文件扩展名的图像 URL。
表格公式:
=image(getURL("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp"))
推荐阅读
- python - 如何使用 np.where 更改多个列值?
- java - 如何访问 Azure 的 Tomcat 日志以进行 Java 应用服务部署
- java - 如何从 xml 元素中删除属性?
- javascript - ReactJS:管理单选按钮行为
- json - 如何使用 JQ 从数组内容创建对象字段
- spring - 以集群模式运行 Spring Cloud Data Flow
- javascript - 如何在 javascript 中获取 rss/atom 提要的内容
- azure - 无法使用服务主体登录 ACR - 访问被拒绝
- colors - 如何更改嵌入在 QTableWidget 中的 QComboBox 的颜色?
- python - 如何设置 StaticLiveServerTestCase 以使用 websockets