Search code examples
google-apps-scriptgoogle-sheetsexport-to-excel

Google apps script to email google spreadsheet excel version


I would like to write an apps script to email an excel version of my Google Spreadsheet. I know I can save the spreadsheet as an Excel file. I am not sure if I can use the script to email the excel version out as an attachment. How can this be done?


Solution

  • After an answer on another recent post (Thomas van Latum), I tried the suggested doc api and get an interesting result... here is the test code I used and that is working nicely except the file is in xlsx format, not in xls but this is not necessarily an issue these days :

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

    note : if you don't rename it, its default name is Export.xlsx , it might be more usefull to get its ID to use it later... so the last line could be like this instead :

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

    EDIT : to trigger the authorization process, try a small function like this, run it from the script editor

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