首页 文章

如何将Google文档文件转换为Excel文件(XLSX)

提问于
浏览
4

该图像显示了更新的代码 .
1

var“xlsFile”未定义,为什么?如何使用(GoogleDocs)ScriptEditor将Googledocs文件转换为Excel文件

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 = '#'
      exportToXls(id)
 }

    function exportToXls(id){
       var mute =  {muteHttpExceptions: true };
       var name = DriveApp.getFileById(id).getName()
       var url = 'https://docs.google.com/feeds/';
       var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',     mute).getBlob()
       var xlsfile = DocsList.createFile(doc).rename(name+'.xlsx')
    }

2 回答

  • 4

    使用Drive API,我们可以获得有关文件的更多信息,而不是通过DriveApp方法获得的信息 . 看看file data,特别是 exportLinks . 这些链接包含让我们获得XLS文件的魔力 . (为了好玩,在 file 被分配后放置一个断点,并检查你必须使用哪些信息 . )

    此脚本使用Advanced Drive Service,其中must be enabled . this gist中提供了一个带有错误检查的更完整版本 .

    /**
     * Downloads spreadsheet with given file id as an Excel file.
     * Uses Advanced Drive Service, which must be enabled. * Throws if error encountered.
     *
     * @param {String}   fileId       File ID of Sheets file on Drive.
     */
    function downloadXLS(fileId) {
      var file = Drive.Files.get(fileId);
      var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
    
      var options = {
        headers: {
          Authorization:"Bearer "+ScriptApp.getOAuthToken()
        },
        muteHttpExceptions : true        /// Get failure results
      }
    
      var response = UrlFetchApp.fetch(url, options);
      var status = response.getResponseCode();
      var result = response.getContentText();
      if (status != 200) {
        // Get additional error message info, depending on format
        if (result.toUpperCase().indexOf("<HTML") !== -1) {
          var message = strip_tags(result);
        }
        else if (result.indexOf('errors') != -1) {
          message = JSON.parse(result).error.message;
        }
        throw new Error('Error (' + status + ") " + message );
      }
    
      var doc = response.getBlob();
      //DocsList.createFile(doc).rename(file.title + '.xlsx') // Deprecated
      DriveApp.createFile(doc).setName(file.title + '.xlsx');
    }
    
  • 9

    下面的代码使用oAuthConfig,现在已弃用 . 请改用Mogsdad . importXLS函数使用驱动器API仍然有效 .


    你会发现许多帖子说这是不可能的,而且(有几个)其他人说你可以......显然你可以!

    Mogsdad的回答(同时)带来了一个优雅的解决方案,使用驱动服务,这是另一个,所以你有一个选择;-)

    作为奖励,我添加了相反的过程,如果你需要它 .

    使用类似于我在测试函数中使用的函数调用来使其工作 .

    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'
      exportToXls(id)
    }
    
    function exportToXls(id){
      var name = DriveApp.getFileById(id).getName()
      var url = 'https://docs.google.com/feeds/';
      var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
                                  googleOAuth_('docs',url)).getBlob()
      var xlsfile = DocsList.createFile(doc).rename(name+'.xls')
    }
    
    function importXLS(){
      var files = DriveApp.searchFiles('title contains ".xls"');
      while(files.hasNext()){
        var xFile = files.next();
        var name = xFile.getName();
        if (name.indexOf('.xls')>-1){
          var ID = xFile.getId();
          var xBlob = xFile.getBlob();
          var newFile = { title : name+'_converted',
                         key : ID
                        }
          file = Drive.Files.insert(newFile, xBlob, {
            convert: true
          });
        }
      }
    }
    

相关问题