Search code examples
javascriptgoogle-apps-scriptgoogle-apigoogle-apps

Google script xls attachment not displaying


any thoughts as to why this script emails an attachment but the attachment is not the correct spreadsheet, and looks like some sort of google error page.

enter image description here

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("[email protected]", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
    
  } catch (f) {
    Logger.log(f.toString());
  }
}


Solution

  • I guess API has changed. You can try Drive REST API(v3) instead. Replace

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

    to

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

    I tested and it worked. Of course you first should get your own API key, etc, at 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, but notice that you cannot try your own API key here.