将Excel附件,Outlook或Gmail中的数据传输到Google表格

问题描述 投票:-1回答:1

我每天都会在Outlook中收到一封带有Excel工作表的电子邮件。

我正在使用Google数据工作室和Google表格中的仪表板/模板。为了使此工作顺利进行,我需要将数据从Excel工作表自动传输到我的Google工作表。这可能吗?

我的第一想到的是将附加的Excel工作表发送到我的gmail,因为我可以从此处编写一个脚本,该脚本从gmail获取数据。这比我想象的要复杂。

也许是VBA代码,可以将附加的Excel文件传输到Google驱动器,然后从那里我可以更新我的Google工作表?这可能吗?

注意:我没有足够的经验来从头开始编写VBA / APP脚本。

excel vba google-apps-script google-sheets outlook-vba
1个回答
1
投票

Q: OP询问:是否可以将作为Outlook附件接收的Excel电子表格传输到Google驱动器,然后将其更新为Google表格格式?

A:是的。


Q:为满足OP的目标,需要执行哪些离散步骤?A:1-在Outlook中编写宏,以将电子邮件和Excel附件自动转发到OP的GMail帐户;专门用于登录Google表格的帐户。为了这个答案的目的,尽管这方面很简单,但是这被视为不在主题之列。

2-在Google云端硬盘中创建一个文件夹(或文件夹/子文件夹),可以在其中保存Excel电子表格。这可以手动完成或通过脚本完成。 “手动”更容易,“按脚本”更有趣并且提供更大的灵活性。

3-运行Google脚本以访问OP的Gmail帐户,识别Excel附件(例如,以'xls','xlsx','xlsm'结尾的文件-可以添加其他变体),并将Excel文件保存到Google云端硬盘文件夹。在每个相关电子邮件上附加一个“标签”,以便仅处理新的未处理的消息。

4-运行Google脚本以访问Google云端硬盘文件夹/子文件夹,并将Excel电子表格转换为Google表格。


如评论中所述,此主题以前曾以一种或另一种形式提出过很多次:Is there any google API which could save gmail message attachments to google drive?Convert all xls files available in a folder into “Google Doc Spreadsheets”?是两个很好的例子。 Google搜索将在StackOverflow和其他来源上揭示许多其他主题。

但是Google服务(文档,脚本,API等)正在不断增强。此开发的副产品之一是某些方法被中断,这可能使以前的正确答案变得过时。

[不幸的是,在GmailToDrive()的2018年1月答复中提供了出色的Is there any google API which could save gmail message attachments to google drive?功能。 Google Advanced Drive Service和Drive API在2018年发生了变化,而出色的答案现在是最后一个障碍。

提供以下代码是为了提供对2019年2月的更新。该答案的基础是Mr.Rebot提供的GmailToDrive()函数,但已针对Excel文件进​​行了修改。


触发器

该代码应设置为时间驱动的可安装触发器。频率因情况而异。 OP可以自己进行评估。还有其他资料可以解释这一点。


Drive API

OP必须激活Drive API(高级服务以及Google Cloud Platform API仪表板)。为了清楚起见,此答案的末尾简要介绍了步骤。


代码

// GLOBALS
// Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['xls', 'xlsx', 'xlsm'];

//Name of the folders in google drive in which files will be put
var homeFolder = "009-StackExchange"; // a folder branching from the root
var ExcelFolderName = "010-GmailToDrive"; // sub folder of "homeFolder"

//Name of the label which will be applied after processing the mail message
var emaillabelName = 'GmailToDrive';

function so54755021()
// an adaptation of function GmailToDrive()
{

  //build query to search emails
  var query = '';

  // loop through the filestoextract and add to query
  for (var i in fileTypesToExtract) {
    query += (query == '' ? ('filename:' + fileTypesToExtract[i]) : (' OR filename:' + fileTypesToExtract[i]));
  }
  //Logger.log("DEBUG: #01 the query is: " + query); //DEBUG

  query = 'in:inbox has:nouserlabels ' + query;
  //Logger.log("DEBUG: #02 the query is: " + query); //DEBUG

  var threads = GmailApp.search(query);
  //Logger.log("DEBUG: threads = " + threads + "; threads length = " + threads.length); //DEBUG

  var label = getGmailLabel_(emaillabelName);
  //Logger.log("DEBUG: label = " + label); //DEBUG (GmailToDrive)

  var parentFolder;

  if (threads.length > 0) {
    //Logger.log("DEBUG: threads length is more than zero");//DEBUG

    //Logger.log("DEBUG: folder name = " + folderName); //DEBUG  
    //parentFolder = getFolder_(folderName); // subroutine

    // build sub-folder if necessary
    createDriveFolder(homeFolder, ExcelFolderName);
    parentFolder = homeFolder;

  }


  for (var i in threads) {
    var mesgs = threads[i].getMessages();
    for (var j in mesgs) {
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for (var k in attachments) {
        var attachment = attachments[k];
        //Logger.log("DEBUG: attachment: " + attachment);//DEBUG

        var isExcelType = checkIfExcel_(attachment);
        //Logger.log("DEBUG: isExceltype = " + isExcelType);//DEBUG

        if (!isExcelType) continue;

        // Copy the Blob
        var attachmentBlob = attachment.copyBlob();
        //Logger.log("DEBUG: attachmentblob = " + attachmentBlob);//DEBUG

        var ExcelFolderObject = DriveApp.getFoldersByName(ExcelFolderName).next();

        //Create the Excel file in Google Drive
        var file = ExcelFolderObject.createFile(attachmentBlob);

        // get the file name and ID
        var fileid = file.getId();
        var filename = file.getName();
        // Logger.log("DEBUG: file = " + file + ", and ID = " + fileid + ", and file name: " + filename);//DEBUG
        var fileType = file.getMimeType()
        // Logger.log("DEBUG: the MIME type is " + fileType);//DEBUG

        // copy the Blob again in preparation for conversion
        var xBlob = file.getBlob();

        // get the folder ID to copy the file
        var folderId = DriveApp.getFoldersByName(ExcelFolderName).next().getId();

        // set parameters for the new file
        var newFile = {
          title: filename + '_converted',
          key: fileid,
          parents: [{
            "id": folderId
          }]

        }

        // convert the file
        var convfile = Drive.Files.insert(newFile, xBlob, {
          convert: true
        });
        // Logger.log("DEBUG: the converted file is " + convfile);//DEBUG

      }
    }

    // Add the label to the Gmail item
    threads[i].addLabel(label);
  }
}


// If necessary, create the label in GMail
function getGmailLabel_(name) {
  var label = GmailApp.getUserLabelByName(name);
  if (label == null) {
    label = GmailApp.createLabel(name);
  }
  return label;
}

function createDriveFolder(baseFolder, folderName) {

  var baseFolderObject = DriveApp.getFoldersByName(baseFolder).next();
  //Logger.log("DEBUG: basefolderobject = " + baseFolderObject);//DEBUG
  var folders = DriveApp.getFoldersByName(baseFolder).next().getFolders();
  //Logger.log("DEBUG: folders: "+folders);//DEBUG

  // set variable to detect a match
  var foldermatch = 0;

  //Loop through folders
  while (folders.hasNext()) {

    var folder = folders.next();
    //Logger.log(DEBUG: folder.getName());//DEBUG

    // If the folder name matches
    if (folder.getName() == folderName) {

      // update the match variable
      foldermatch = 1;
      // Logger.log("DEBUG: there's a match/folder exists: " + folder.getName());//DEBUG
    }
  }

  // Do something is there is a match
  if (foldermatch != 0) {
    //Logger.log("DEBUG: There was a match so do NOTHING");//DEBUG


  } else {
    // Logger.log("DEBUG: There was no match so create the folder"); //DEBUG
    baseFolderObject.createFolder(folderName);
  }

  // The folder already existed, or it has been created. Either way, our work is done.
  return;
}


// this function will check for filextension type.
// and return boolean
function checkIfExcel_(attachment) {
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length - 1].toLowerCase();
  if (fileTypesToExtract.indexOf(fileExtension) != -1) return true;
  else return false;
}


启用驱动器Api

1-从脚本编辑器中,选择资源>高级Google服务;选择云端硬盘API,然后将开关滑动至开启。Advanced Google Services


2-单击指向“ Google Cloud Platform API仪表板”的链接]


3-Google Cloud Platform-API和服务屏幕在新窗口中打开。点击链接以启用API和服务Google Cloud Platform - Enable APIs and Services


4-搜索“驱动器”,然后单击驱动器API的选项。Search for "drive"


5-单击Drive API的“启用”按钮enter image description here


6-系统将显示Drive API详细信息;请注意,驱动器API已启用。然后关闭此窗口。the Drive API is enabled


7-在“高级Google服务”屏幕(一直保持打开状态)上,单击确定。您已经准备好运行脚本。

© www.soinside.com 2019 - 2024. All rights reserved.