2

我想要一个谷歌脚本,只要有编辑,它就会自动将电子表格导出到 .XLSX,覆盖任何以前的版本。使用这个答案作为模板,我创建了以下代码:

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  var r = s.getActiveCell();
  if( r.getColumn() != 1 ) { //checks the column
    var row = r.getRow();
    var time = new Date();
    time = Utilities.formatDate(time, "GMT-08:00 ", "MM/dd/yy, hh:mm:ss");
    SpreadsheetApp.getActiveSheet().getRange('A' + row.toString()).setValue(time); 

    var id = 'MY_SPREADSHEET_KEY'
    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')
  };
 };

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"};
}

但是,它似乎没有导出。或者,如果它正在导出,我不确定这是在哪里发生的。

有任何想法吗?

4

2 回答 2

4

由于谷歌 API 的更改,Serge 的一些脚本不再可用,我发布了我的脚本,该脚本基本上将当前电子表格导出到xlsx(请注意xls不支持导出到)并将其保存到名为Exports. 在执行此操作之前,它会删除以前的xlsx文件并仅保留最新的文件,这样您就不需要计算时间或更改任何单元格:

function exportAsxlsx() {
  var spreadsheet   = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var file          = Drive.Files.get(spreadsheetId);
  var url           = file.exportLinks[MimeType.MICROSOFT_EXCEL];
  var token         = ScriptApp.getOAuthToken();
  var response      = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  var blobs   = response.getBlob();
  var folder = DriveApp.getFoldersByName('Exports');
  if(folder.hasNext()) {
    var existingPlan1 = DriveApp.getFilesByName('newfile.xlsx');
    if(existingPlan1.hasNext()){
      var existingPlan2 = existingPlan1.next();
      var existingPlanID = existingPlan2.getId();
      Drive.Files.remove(existingPlanID);
    }
  } else {
    folder = DriveApp.createFolder('Exports');
  }
  folder = DriveApp.getFoldersByName('Exports').next();
  folder.createFile(blobs).setName('newfile.xlsx')
}

如果没有,它还会创建特定文件夹。您可以使用这些命令并查看这些类是如何工作的。请注意,您需要Resources -> Advanced Google Services -> Drive API通过切换到Google Developers Console 和从 Google Developers Console 启用 Drive API(请参阅此处on的详细说明)。我还设置了一个简单的触发器,在每次编辑时调用这个函数。这可以通过以下方式完成:。您不需要添加任何库。Resources -> Current project's triggers -> Add a new trigger

于 2016-07-04T14:40:18.727 回答
2

确实不是!可能是因为oAuth功能没有得到正确的授权,也可能是因为简单的onEdit不允许做这种操作。

您必须创建一个可安装的触发器menu>ressource>current trigger>create)。

试试下面的这个脚本并运行这个authorize函数。

我还更改了一些细节:timeZone直接取自电子表格,id也取自活动电子表格。

另请注意,新创建的 XLSX 不会覆盖任何以前的文件,您将获得许多具有相同名称的文件!如果您只想保留最新版本,那么您应该自己处理,获取所有文档名称“新文件”并file.setTrashed(true)在创建新文件之前删除它们。

这就像这两行代码一样简单:

var oldVersions = DocsList.find('newfile.xls');
for(var d in oldVersions){oldVersions[d].setTrashed(true)};

编码 :

function myOnEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var r = s.getActiveCell();
  if( r.getColumn() != 1 ) { //checks the column
    var row = r.getRow();
    var time = new Date();
    time = Utilities.formatDate(time, ss.getSpreadsheetTimeZone(), "MM/dd/yy, hh:mm:ss");
    var id = ss.getId();
    s.getRange('A' + row.toString()).setValue(time); 
    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')  
  }
}

function authorise(){
  // function to call to authorize googleOauth
  var id=SpreadsheetApp.getActiveSpreadsheet().getId();
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
                            googleOAuth_('docs',url)).getBlob()
}
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"};
}

编辑:根据您的评论,这是一个仅每 30 秒保存一次的版本(如果未进行编辑,则保存更多)。如有必要,您可以轻松地将时间值更改为另一个间隔。

重新运行授权函数以初始化 scriptProperty。

function myOnEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var r = s.getActiveCell();
  if( r.getColumn() != 1 ) { //checks the column
    var row = r.getRow();
    var time = new Date();
    time = Utilities.formatDate(time, ss.getSpreadsheetTimeZone(), "MM/dd/yy, hh:mm:ss");
    var id = ss.getId();
    s.getRange('A' + row.toString()).setValue(time); 
    var lastSaveTime = new Date(Utilities.jsonParse(ScriptProperties.getProperty('exportTime')));
    var now = new Date().getTime();
    Logger.log(now - lastSaveTime.getTime())
    if (now - lastSaveTime.getTime() > 60000){ // delete every minute
      var oldVersions = DocsList.find('newfile.xls');
      for(var d in oldVersions){oldVersions[d].setTrashed(true)};
    }
    if (now - lastSaveTime.getTime() > 30000){ // save every 30"
      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')  
      ScriptProperties.setProperty('exportTime',Utilities.jsonStringify(new Date()));
    }
  }
}

function authorise(){
  // function to call to authorize googleOauth + initialize the TIMER
  ScriptProperties.setProperty('exportTime',Utilities.jsonStringify(new Date()));
  var id = SpreadsheetApp.getActiveSpreadsheet().getId();
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
                                googleOAuth_('docs',url)).getBlob()
}

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"};
}
于 2013-10-16T09:35:08.293 回答