Google应用脚本:将电子表格通过电子邮件发送为excel

Bha*_*vin 4 google-apps-script google-drive-api

如何创建一个将电子表格作为excel文件附加的应用脚本并将其通过电子邮件发送到某个电子邮件地址?

有关于如何做到这一点#2的一些旧帖子但是他们现在似乎已经过时,似乎工作.

谢谢.

ter*_*era 5

看起来@Christiaan Westerbeek的回答是现实的,但自从他的帖子以来已经过去了一年,我认为他需要对上面提到的剧本进行一些修改.

var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
Run Code Online (Sandbox Code Playgroud)

这行代码有问题,可能exportLinks已经折旧了.当我执行他的代码时,它给出了以下效果的错误:

TypeError:无法application/vnd.openxmlformats-officedocument.spreadsheetml.sheet从undefined中读取属性" ".

解决方法如下:

上面一行代码中的URL基本上是"下载为xlsx"的URL,可用于直接将电子表格下载为您从中获取的xlsx文件 File> Download as > Microsoft Excel (.xlsx)

这是格式:

https://docs.google.com/spreadsheets/d/<<<ID>>>/export?format=xlsx&id=<<<ID>>> 其中<< >>应替换为您的文件的ID.

点击此处可轻松了解如何从Google工作表的网址中提取ID.


Chr*_*eek 3

这是一个最新且有效的版本。此 Google Apps 脚本正常工作的先决条件之一是必须启用Drive API v2高级 Google 服务。通过Resources -> Advanced Google Services... -> Drive API v2 -> on在您的 Google Apps 脚本中启用它。然后,该窗口会告诉您,您必须在 Google Developers Console 中启用此服务。点击链接并在那里启用该服务!完成后,只需使用此脚本即可。

/**
 * Thanks to a few answers that helped me build this script
 * Explaining the Advanced Drive Service must be enabled: http://stackoverflow.com/a/27281729/1385429
 * Explaining how to convert to a blob: http://ctrlq.org/code/20009-convert-google-documents
 * Explaining how to convert to zip and to send the email: http://ctrlq.org/code/19869-email-google-spreadsheets-pdf
 * New way to set the url to download from by @tera
 */
function emailAsExcel(config) {
  if (!config || !config.to || !config.subject || !config.body) {
    throw new Error('Configure "to", "subject" and "body" in an object as the first parameter');
  }

  var spreadsheet   = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var file          = Drive.Files.get(spreadsheetId);
  var url           = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
  var token         = ScriptApp.getOAuthToken();
  var response      = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  var fileName = (config.fileName || spreadsheet.getName()) + '.xlsx';
  var blobs   = [response.getBlob().setName(fileName)];
  if (config.zip) {
    blobs = [Utilities.zip(blobs).setName(fileName + '.zip')];
  }

  GmailApp.sendEmail(
    config.to,
    config.subject,
    config.body,
    {
      attachments: blobs
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

更新:我更新了设置下载网址的方法。通过 file.exportLinks 集合执行此操作不再有效。感谢@tera 在他的回答中指出了这一点。