Google Apps脚本:将电子表格另存为ODS以进行本地备份

时间:2014-06-30 15:05:02

标签: excel csv google-apps-script backup ods

我可以用一只手。我的公司广泛使用Google表格,当我们失去互联网连接时,我们需要一种方法来访问文件。

我无法在此网站上找到任何可以通过脚本从Google表格创建xls或ods的示例。

我编写了一种创建csv备份的方法,可以从本地Google云端硬盘文件夹访问。当与每小时触发器一起使用时,此脚本会创建过去一小时内修改过的任何电子表格的每张表的csv文件,将它们放在一个文件夹中,并将其拉到专门用于备份的文件夹中。从那里我可以将zip移动到我们的本地服务器。

function backUpMaker() {
  var backupFolderId = '<Id of Backup Folder>';
  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 lastUpdate = sheet.getLastUpdated();
    var timeHourAgo = new Date();
    timeHourAgo = timeNow - 3600000;
    if(lastUpdate >= timeHourAgo){
      var sheetId = sheet.getId();
      var csv = eachSheet(sheetId,newFolderId); 
    }
  }
  var backupFolder = DocsList.getFolderById(backupFolderId);
  try{
    backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
  } catch(err) {
    Logger.log(err);
  }
  newFolder.setTrashed(true);
}

function eachSheet(key,newFolderId) {
  var ss = SpreadsheetApp.openById(key);
  var ssId = ss.getId();
  var ssName = ss.getName();
  var howManySheets = ss.getNumSheets();
  try{
   for (var sheetIndex=0; sheetIndex < howManySheets; sheetIndex++) {   
     var activeSheet = ss.getSheets()[sheetIndex];
     var activeName = activeSheet.getName();
     if(activeName != 'Dropdowns'){     //Skip a hidden sheet used for validation on many of our spreadsheets
      var activeId = activeSheet.getSheetId();
      var time = new Date();
      var fileName = time + " Backup: " + ssName + " " + activeName + ".csv";
      var csv = contentCSV(ssId,activeId);
      var folder = DocsList.getFolderById(newFolderId);  
      folder.createFile(fileName, csv, 'text/plain');
     }
   } 
  } catch(err) {
    Logger.log(err)
  }
}

function contentCSV(key,gid) {
  var file = DocsList.getFileById(key);  
  var response =     UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key + 
                "&gid=" + gid + "&exportFormat=csv", oAuth());
  var fileText = response.getContentText();  
  return fileText;
}

function oAuth() {
  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",
  };
  return requestData;
}

如何将其修改为od而不是csv?或者有更好的方法来保存备份吗?谢谢你的帮助!

工作代码如下,感谢@ serge-insas的输入:

注意:要使其工作,请输入备份文件夹的ID密钥,然后通过注释掉其他选项来选择ods或xlsx。然后你需要为backUpMaker()设置一个定时的每小时触发器。日志将捕获暂时移动的文件的错误。这是:

function backUpMaker() {
  var backupFolderId = '0B5--------------------1ZX1k';
  //var exportFormat = 'ods';
  var exportFormat = 'xlsx';
  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 lastUpdate = sheet.getLastUpdated();
    var timeHourAgo = new Date();
    timeHourAgo = timeNow - 3600000;
    if(lastUpdate >= timeHourAgo){
      try{
      var key = sheet.getId();
      var name = sheet.getName();
      var fileName = timeNow + " Backup: " + name + "." + exportFormat;
      var blob = contentBackup(key,exportFormat);
      var folder = DocsList.getFolderById(newFolderId);  
      folder.createFile(blob).rename(fileName);
      } catch(err){
        Logger.log(err);
      }
    }
  }
  var backupFolder = DocsList.getFolderById(backupFolderId);
  try{
    backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
  } catch(err) {
    Logger.log(err);
  }
  newFolder.setTrashed(true);
}

function contentBackup(key,exportFormat) {
  try{
    if(exportFormat == 'xlsx'){
      exportFormat = 'xls';
    }  
    var file = DocsList.getFileById(key);  
    var response =     UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key + 
                  "&exportFormat=" + exportFormat, oAuth());
    var fileBlob = response.getBlob();  
    return fileBlob;
    } catch(err) {
    Logger.log(err)
    }
}

function oAuth() {
  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",
  };
  return requestData;
}

1 个答案:

答案 0 :(得分:0)

您的代码只需很少的更改即可获取ods文件。

2个不同之处:urlFetch中请求的格式变为“ods”,返回的对象不再是字符串,而是blob。

除此之外,我保留了您编写的所有工作表选择功能,它似乎也可以正常工作。 (你干得好!)。

以下是我从您那里复制的完整代码,并按照描述进行了更改。我的测试工作正常。

function backUpMaker() {
  var backupFolderId = '0B3qS--------------TXdlY2M';
  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 lastUpdate = sheet.getLastUpdated();
    var timeHourAgo = new Date();
    timeHourAgo = timeNow - 3600000;
    if(lastUpdate >= timeHourAgo){
      var sheetId = sheet.getId();
      var csv = eachSheet(sheetId,newFolderId); 
    }
  }
  var backupFolder = DocsList.getFolderById(backupFolderId);
  try{
    backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
  } catch(err) {
    Logger.log(err);
  }
  newFolder.setTrashed(true);
}

function eachSheet(key,newFolderId) {
  var ss = SpreadsheetApp.openById(key);
  var ssId = ss.getId();
  var ssName = ss.getName();
  var howManySheets = ss.getNumSheets();
  try{
   for (var sheetIndex=0; sheetIndex < howManySheets; sheetIndex++) {   
     var activeSheet = ss.getSheets()[sheetIndex];
     var activeName = activeSheet.getName();
     if(activeName != 'Dropdowns'){     //Skip a hidden sheet used for validation on many of our spreadsheets
      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);
     }
   } 
  } catch(err) {
    Logger.log(err)
  }
}

function contentODS(key,gid) {
  var file = DocsList.getFileById(key);  
  var response =     UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key + 
                "&gid=" + gid + "&exportFormat=ods", oAuth());
  var fileBlob = response.getBlob();  
  return fileBlob;
}

function oAuth() {
  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",
  };
  return requestData;
}