Google 脚本 xls 附件未显示

Google script xls attachment not displaying

关于此脚本为何通过电子邮件发送附件但附件不是正确的电子表格,并且看起来像某种 google 错误页面的任何想法。

function getGoogleSpreadsheetAsExcel(){
  
  try {
    
    var ss = SpreadsheetApp.getActive();
    
    var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
    Logger.log(url);
    
    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };
    
    var blob = UrlFetchApp.fetch(url, params).getBlob();
    
    blob.setName(ss.getName() + ".xlsx");
    
    MailApp.sendEmail("youremail@email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
    
  } catch (f) {
    Logger.log(f.toString());
  }
}

我想 API 已经改变了。您可以尝试 Drive REST API(v3) 代替。替换

var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();

var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + 
  "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
  "{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();

我测试过并且有效。当然,您首先应该在 API Manager. Then you can try some APIs like simple GET requests at APIs Explorer. Or you can try some APIs, in this case Files: export, also at the documentation page itself 获得您自己的 API 密钥等,但请注意,您不能在这里尝试您自己的 API 密钥。

这是@sangbok 帮助更新的代码:

function getGoogleSpreadsheetAsExcel(){
  
  try {
    
    var ss = SpreadsheetApp.getActive();
    var sheet = DriveApp.getFileById(ss.getId());
    
    // sets sharing to public - to send out email.
    sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
    
    var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOURAPIKEYGOESHERE4";
    var blob = UrlFetchApp.fetch(url).getBlob();
    
    Logger.log(url);
    
    blob.setName(ss.getName() + ".xlsx");
    
    var now = new Date();
    
    MailApp.sendEmail("YOUREMAILADDRESSGOESHERE", "EMAIL SUBJECT " + now , "EMAIL BODY " + now , {attachments: [blob]});
    
  } catch (f) {
    Logger.log(f.toString());
  }
    // returns the file back to Private access
    sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}