使用GAS将Google电子表格转换为XLSX或ODS

时间:2014-07-27 21:10:46

标签: google-apps-script google-sheets

我想将一些谷歌电子表格转换为Excel(xlsx首选) 我已经阅读了几个关于如何实现这一点的线索,但我无法让它运行 我读过的帖子包括Google Apps Script: Save Spreadsheet as ODS for Local BackupGoogle apps script to email google spreadsheet excel version

为了接近代码,我发现并获得有关它为什么不起作用的更多信息,我修改了我发现的代码,它只处理了一些文件,并且还尝试了catch-catch除去。

****************** Not working code **************
function contentODS(key, gid) 
{
   var file = DocsList.getFileById(key); 

   var fetchParameters = oAuth();

   var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key + "&gid=" + gid + "&exportFormat=ods";
   var response = UrlFetchApp.fetch(url, fetchParameters);

   var fileBlob = response.getBlob();  
   return fileBlob;
}

function oAuth()
{ // https://stackoverflow.com/questions/24493203/google-apps-script-save-spreadsheet-as-ods-for-local-backup
  var oauthConfig = UrlFetchApp.addOAuthService("spreadsheets");
  var scope = "https://spreadsheets.google.com/feeds" 
  oauthConfig.setConsumerKey("anonymous");
  oauthConfig.setConsumerSecret("anonymous");
  oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
  oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");    
  oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");   

  var requestData =
  {
    "oAuthServiceName":   "spreadsheets",
    "oAuthUseToken":      "always",
    "muteHttpExceptions": true,
    "method":             "DELETE",
  };
  return requestData;
}

function eachSheet(key, newFolderId)
{
  var ss = SpreadsheetApp.openById(key);
  var ssId = ss.getId();
  var ssName = ss.getName();
  var howManySheets = ss.getNumSheets();

  for (var sheetIndex=0; sheetIndex < howManySheets; sheetIndex++)
  {   
     var activeSheet = ss.getSheets()[sheetIndex];
     var activeName = activeSheet.getName();
     var activeId = activeSheet.getSheetId();
     var time = new Date();
     var fileName = time + " Backup: " + ssName + " " + activeName + ".ods";
     var blob = contentODS(ssId, activeId);
     var folder = DocsList.getFolderById(newFolderId);  
     folder.createFile(blob).rename(fileName);
   } 
}

function backUpMaker()
{
  var backupDirectory = 'Backup';
  var folders = DriveApp.getRootFolder().getFoldersByName(backupDirectory);
  var backupFolderId = undefined;
  if (folders.hasNext()) backupFolderId = folders.next().getId();
  else return;  // File doe not exist

  var timeNow = new Date();  
  var newFolder = DocsList.createFolder(timeNow);
  var newFolderId = newFolder.getId();
  newFolder.addToFolder(DocsList.getFolderById(backupFolderId));
  newFolder.removeFromFolder(DocsList.getRootFolder());
  var sheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  while (sheets.hasNext())
  {
    var sheet = sheets.next();
    var name = sheet.getName();

    var filesToSave = [ 'My-Agenda', 'My-Kalender' ];
    var numFiles = filesToSave.length;

    for (var i=0; i<numFiles; i++)
    {
       if (name == filesToSave[i])
       {
          var sheetId = sheet.getId();
          var csv = eachSheet(sheetId, newFolderId); 
          break;
       }  
    }   
  }
  var backupFolder = DocsList.getFolderById(backupFolderId);
  var newFiles = newFolder.getFiles();
  var numFiles = newFiles.length;

  if (numFiles > 0)
  {
     var nameZipFile = timeNow + '.zip';
     backupFolder.createFile(Utilities.zip(newFiles, nameZipFile));
  } 

  newFolder.setTrashed(true);
}

var response = UrlFetchApp.fetch(url, fetchParameters);执行备份计算机失败 并表示服务电子表格验证失败

我应该怎么做才能使它发挥作用。

1 个答案:

答案 0 :(得分:4)

您可以使用Advanced Drive Service获取导出网址,并使用脚本的OAuth2令牌下载文件。

function exportAsExcel(spreadsheetId) {
  var file = Drive.Files.get(spreadsheetId);
  var url = file.exportLinks['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });
  return response.getBlob();
}

function test() {
  var spreadsheetId = 'SPREADSHEET ID HERE';
  DriveApp.createFile(exportAsExcel(spreadsheetId));
}