2

我想编写一个应用程序脚本来通过电子邮件发送我的 Google 电子表格的 excel 版本。我知道我可以将电子表格保存为 Excel 文件。我不确定是否可以使用脚本将 excel 版本作为附件通过电子邮件发送出去。如何才能做到这一点?

4

5 回答 5

2

对最近的另一篇文章Thomas van Latum)进行回答之后,我尝试了建议的 doc api 并得到了一个有趣的结果......这是我使用的测试代码,除了文件是 xlsx 格式而不是 xls 之外,它运行良好但是现在这不一定是一个问题:

function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey('anonymous');
  oAuthConfig.setConsumerSecret('anonymous');
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

function test(){
var id = 'spreadsheet_ID'
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
DocsList.createFile(doc).rename('newfile.xls')
}

注意:如果你不重命名它,它的默认名称是Export.xlsx,获取它的 ID 以便以后使用它可能更有用......所以最后一行可能是这样的:

var xlsfileID = DocsList.createFile(doc).getId()

编辑:触发授权过程,尝试这样的小功能,从脚本编辑器运行它

function autorise(){
  // function to call to authorize googleOauth
  var id=SpreadsheetApp.getActiveSpreadsheet().getId();
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
                              googleOAuth_('docs',url)).getContentText();  
}
于 2012-10-12T22:25:47.667 回答
1

因为我花了大约四个小时玩 Rumpelstiltskin,因为在谷歌搜索“谷歌文档脚本发送 excel 附件”或类似内容时,你可以找到旧电子表格版本和旧 OAUTH 的典型非常旧的代码片段(即你想要一个电子表格,将其转换为 Excel 格式并作为电子邮件附件发送)确实有效,我终于找到了解决方案。

要创建实际的附件内容,假定的 res.getContent() 或 res.getBlob() 或 res.getBytes 都不起作用。这些提示具有误导性!

唯一对我有用的是 response.getBlob().getContent()!

整个代码:

function sendCurrentDocAsEmail() {
  var driveService = getDriveService();
  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId(); 

  var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
  var email = "recipient@demo.com"
  var subject = "Here be Subjects";
  var body = "Don't even think about learning how to code. It's wasted time.";
  var file = Drive.Files.get(ssID );
  var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];

  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + driveService.getAccessToken()
    }
  });

  var attachments = [{
    fileName:sheetName+".xlsx",
    content: response.getBlob().getBytes(), // this single line has cost me hours!
    mimeType:"application//xls",
    headers: {
      Authorization: 'Bearer ' + driveService.getAccessToken()
    }
  }];

  MailApp.sendEmail(email,subject ,body, {attachments:attachments}); 

}

其中 getDriveService() 是https://github.com/googlesamples/apps-script-oauth2上 Google 的“OAuth2 for Apps Script”自述文件中的一个函数

于 2015-08-01T08:12:18.923 回答
1

最新的工作版本如下。基于示例,即与之前的答案类似,但使用 Google 服务帐户,该帐户不需要人工通过链接来接收令牌。您必须从 Google 安装 Oath 库,说明非常清楚。

var PRIVATE_KEY = 'xxx'
var CLIENT_EMAIL = 'xxx';
var USER_EMAIL=Session.getActiveUser().getEmail()

function getOathService() {
  return OAuth2.createService('GoogleDrive:' + USER_EMAIL)
      // Set the endpoint URL.
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      // Set the private key and issuer.
      .setPrivateKey(PRIVATE_KEY)
      .setIssuer(CLIENT_EMAIL)

      // Set the name of the user to impersonate. This will only work for
      // Google Apps for Work/EDU accounts whose admin has setup domain-wide
      // delegation:
      // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
      .setSubject(USER_EMAIL)

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getScriptProperties())

      // Set the scope. This must match one of the scopes configured during the
      // setup of domain-wide delegation.
      .setScope('https://www.googleapis.com/auth/drive');
}


function sendEmail() { 
  var oathService = getOathService();
  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId(); 
  var file = Drive.Files.get(ssID );
  var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];

  var file = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + oathService.getAccessToken()
    }
  });
   var attachments = [{
    fileName:'xxx.xls',//TODO DATE
    content: file.getBlob().getBytes(), 
    mimeType:"application//xls",
    headers: {
      Authorization: 'Bearer ' + oathService.getAccessToken()
    }
  }];

  MailApp.sendEmail('email@domain.com', 'xxx', 'Hi,\n\nPlease see the last data in attachment',{attachments:attachments});
}
于 2016-07-15T00:55:13.167 回答
0

对我有用的那个:

var AUTH_TOKEN = "Enter your OAuth_Token"; 

ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var url = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ ssID + "&exportFormat=xls"; 

//Add &gid=x at the end of above url if you only want a particular sheet

var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var attachments = [{fileName:"<Filename>.xls", content: res.getContent(),mimeType:"application/vnd.ms-excel"}];

MailApp.sendEmail("<recipient's email id>", "<email subject>", "<email body>", {attachments: attachments});

从这里获取 OAuth 文档和令牌https://developers.google.com/accounts/docs/OAuth2

于 2013-07-14T15:06:54.870 回答
-3

修改后使用以下代码片段以满足您的需要

var file = DocsList.getFileById(FILE_ID);
var attachment = file.getAs('application/vnd.ms-excel'); 
MailApp.sendEmail("abcd@example.com", "Subject", " Body" , {"fileName": "Your_file_name" , "mimeType" : "application/vnd.ms-excel" , "content":attachment.getBytes() } ); 

请注意,此代码未经测试,因此请随时修复可能弹出的一两个错误

于 2012-10-03T16:39:46.593 回答