【问题标题】:How to convert a Google Docs-File to an Excel-File (XLSX)如何将 Google Docs 文件转换为 Excel 文件 (XLSX)
【发布时间】:2015-02-01 07:56:44
【问题描述】:

图片显示了更新的代码。

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

 功能 googleOAuth_(名称,范围){
       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('匿名');
       oAuthConfig.setConsumerSecret('匿名');
       返回 {oAuthServiceName:name, oAuthUseToken:"always"};
    }

 功能测试(){
      var id = '#'
      exportToXls(id)
 }

    函数 exportToXls(id){
       var mute = {muteHttpExceptions: true };
       var name = DriveApp.getFileById(id).getName()
       var url = 'https://docs.google.com/feeds/';
       var doc = UrlFetchApp.fetch(url+'下载/电子表格/Export?key='+id+'&exportFormat=xls', 静音).getBlob()
       var xlsfile = DocsList.createFile(doc).rename(name+'.xlsx')
    }

【问题讨论】:

标签: excel google-apps-script google-sheets google-docs xlsx


【解决方案1】:

使用 Drive API,我们可以获得比 DriveApp 方法更多的文件信息。查看file data,尤其是exportLinks。这些链接包含让我们获得 XLS 文件的魔法。 (为了好玩,在分配file 之后放置一个断点,并检查您必须使用哪些信息。)

此脚本使用Advanced Drive Service,即must be enabledthis 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');
}

【讨论】:

  • Mogsdad,我认为 UrlFetch 需要一个令牌来下载转换后的文件。请看here
  • 感谢@HenriqueAbreu。完全更新了我的生产脚本。
【解决方案2】:

下面的代码使用 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
      });
    }
  }
}

【讨论】:

  • 领先你5分钟!
  • 你只是打字更快了 XD
  • 运行查询时出现的错误。
    Fehler bei der Anfrage für 。 Folgender Code wurde zurückgegeben: 404. Gekürzte Serverantwort: 
  • 你如何尝试这段代码?您是否完全按照我描述的程序进行操作?
  • 我只想将Google Docs文件保存为Excel文件,有这么难吗? @Mogsdad
猜你喜欢
  • 2023-01-19
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多