首页 > 解决方案 > 使用 Google Script 在 GDrive 中获取 XLSX 文件的 URL

问题描述

背景: 我有一个 xlsx 文件,每周都会通过电子邮件发送给我。该文件在使用触发器到达时保存到我的驱动器中。

请求: 我现在想将该文件中的数据复制到谷歌表格仪表板中。首先,我想知道是否有一种方法可以在 google 脚本中以编程方式获取该文件的 URL。手动操作是双击驱动器中的文件,然后单击“使用 Google 表格打开”,然后复制 URL。显然,我不想每周都手动进行。谷歌脚本可以做到这一点吗?

标签: google-apps-script

解决方案


这有帮助吗?我已经发表评论以帮助解释它在做什么。

您需要从 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);
            }
        }
    }
}

推荐阅读