谷歌应用程序脚本,以电子邮件谷歌电子表格excel版本

时间:2012-10-03 15:48:42

标签: google-apps-script

我想编写一个应用脚本来通过电子邮件发送我的Google电子表格的Excel版本。我知道我可以将电子表格保存为Excel文件。我不确定是否可以使用该脚本将excel版本作为附件发送出去。怎么办呢?

5 个答案:

答案 0 :(得分:3)

answer on another recent postThomas 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();  
}

答案 1 :(得分:1)

对我有用的那个:

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文档&amp;你来自https://developers.google.com/accounts/docs/OAuth2

的令牌

答案 2 :(得分:1)

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

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});
}

答案 3 :(得分:0)

因为我花了大约四个小时玩Rumpelstiltskin,因为旧的电子表格版本和旧的OAUTH没有通常非常旧的代码片段,你可以在Google搜索“谷歌文档脚本发送excel附件”或类似的时候找到(即你想要拿现有的电子表格,将其转换为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()是来自Google的“OAuth2 for Apps脚本”自述文件的函数https://github.com/googlesamples/apps-script-oauth2

答案 4 :(得分:-2)

根据您的需要修改后使用以下代码片段

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() } ); 

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