Google应用脚本:循环选项卡以保存到单独的工作表

时间:2014-08-27 13:43:28

标签: google-apps-script google-sheets

我想循环某个工作表的所有单个选项卡(最好跳过需要排除的数组)。对于每个单独的标签,我想将其保存为Google云端硬盘中的单独工作表,标签的标题为文件名。如果文件名已经存在,则应该覆盖它。

我希望能够在所需的脚本中排除一系列工作表(例如,命名为“master”和“test”)。

不幸的是,我对Google Apps脚本的了解还不足以自己编写。任何工作实例都受到高度赞赏。

编辑:这是我如何解决它(总是欢迎改进建议!:-)) EDIT2:更改了deleteSheet行

function copySheetsToSS() {
  var ss = SpreadsheetApp.getActive();
  for(var n in ss.getSheets()){// loop over all tabs in the spreadsheet
    var sheet = ss.getSheets()[n];// look at every sheet in spreadsheet
    var name = sheet.getName();//get name
    if(name != 'master' && name != 'test'){ // exclude some names
      var alreadyExist = DriveApp.getFilesByName(name);// check if already there
      while(alreadyExist.hasNext()){
        alreadyExist.next().setTrashed(true);// delete all files with this name
      }
      var copy = SpreadsheetApp.create(name);// create the copy
      sheet.copyTo(copy).setName(name); // rename copied sheet to same name as SS
      copy.deleteSheet(copy.getSheets()[0]);// delete default Sheet1 from new copy
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您的描述非常准确,以便在代码中轻松翻译...

您应该尝试过,我确信该文档可以让您使其正常运行...运行您自己编写的代码会很有趣并且非常有意义!

这是一个令人沮丧的(对你而言)工作代码的解决方案;-)以及评论中的解释

function copySheetsToSS() {
  var ss = SpreadsheetApp.getActive();
  for(var n in ss.getSheets()){
    var sheet = ss.getSheets()[n];// look at every sheet in spreadsheet
    var name = sheet.getName();//get name
    if(name != 'master' && name != 'test'){ // exclude some names
      var alreadyExist = DriveApp.getFilesByName(name);// check if already there
      while(alreadyExist.hasNext()){
        alreadyExist.next().setTrashed(true);// delete all files with this name
      }
      var copy = SpreadsheetApp.create(name);// create the copy
      sheet.copyTo(copy);// copy content
      copy.deleteSheet(copy.getSheets()[0]);// remove original "Sheet1"
      copy.getSheets()[0].setName(name);// rename first sheet to same name as SS
    }
  }
}