google-apps-script - 使用 Google Script 在 GDrive 中获取 XLSX 文件的 URL
问题描述
背景: 我有一个 xlsx 文件,每周都会通过电子邮件发送给我。该文件在使用触发器到达时保存到我的驱动器中。
请求: 我现在想将该文件中的数据复制到谷歌表格仪表板中。首先,我想知道是否有一种方法可以在 google 脚本中以编程方式获取该文件的 URL。手动操作是双击驱动器中的文件,然后单击“使用 Google 表格打开”,然后复制 URL。显然,我不想每周都手动进行。谷歌脚本可以做到这一点吗?
解决方案
这有帮助吗?我已经发表评论以帮助解释它在做什么。
您需要从 Resources > Advanced Google Services 启用 Drive API。
这会将附件保存到云端硬盘并将其转换为 Google 表格。此时,您可以打开转换后的 Google 表格文件并提取数据以保存到另一个 Google 表格数据。
function doIt()
{
// get where we want to save the file
var destinationFolder = DriveApp.getFolderById("...");
// search for the email with the attachment you want to save
var emailThreads = GmailApp.search("...");
// go through each thread
for(var i = 0, numThreads = emailThreads.length; i < numThreads; ++i)
{
// get all of the emails in the thread
var emailMessages = emailThreads[i].getMessages();
// get all of the messages
for(var j = 0, numMessages = emailMessages.length; j < numMessages; ++j)
{
// get the message
var emailMessage = emailMessages[j];
// we only want messages that are not in the trash
if(emailMessage.isInTrash()) continue;
// get all of the attachments
var emailAttachments = emailMessage.getAttachments({includeInlineImages: false, includeAttachments: true});
// go through all attachments
for(var k = 0, numAttachments = emailAttachments.length; k < numAttachments; ++k)
{
// get the attachment
var emailAttachment = emailAttachments[k];
// save the attachment to the destination folder
var savedFile = destinationFolder.createFile(emailAttachment);
// log the URL of the saved file
Logger.log(savedFile.getUrl());
// create a copy of the file as a Google Sheets file
var sheetsFile = Drive.Files.insert({
"title": "...",
"parents": [{"id": destinationFolder.getId()}]
}, savedFile.getBlob(), {
"convert": true,
"supportsAllDrives": true,
"supportsTeamDrives": true
});
// log the URL and file ID of the converted file
Logger.log(sheetsFile.selfLink);
Logger.log(sheetsFile.id);
}
}
}
}
推荐阅读
- python - 将 find_contours 的结果重新绘制到不同的网格上
- odoo - 通过 Odoo 14 中的 PUT 和 DELETE 方法进行 API 路由
- laravel - 使用 Eloquent 模型重置表上的索引
- jquery - 如何保存可调整大小元素的大小(JQuery UI)
- javascript - 我可以用按钮的时钟打开菜单吗?
- php - 错误:试图访问 null 类型值的数组偏移量(php 8)
- arrays - 用c中给定数组的元素的所有(n个选择k)组合创建一个数组?
- github - Intellij - 无法将现有项目连接到现有的 Github 存储库
- vue.js - Laravel 在 Vue 组件中混合“无法识别的输入”
- ios - swift 5中的日期时间转换