我使用以下代码将电子表格合并到Gdrive上的文件夹中。我试图弄清楚如何组合表格但知道它们的顺序。例如,如果我在名为SS1,SS2,SS3,SS4的文件夹中有4个文件。如何确保统一工作表中的4个选项卡将是SS1,SS2,SS3,SS4,而不是像我现在的代码那样的随机顺序。例如,我的代码可能会吐出像SS2,SS1,SS4,SS3这样的订单。
function mergeSheets() {
/* Retrieve the desired folder */
var myFolder = DriveApp.getFoldersByName(SOURCE).next();
/* Get all spreadsheets that resided on that folder */
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
/* Create the new spreadsheet that you store other sheets */
var newSpreadSheet = SpreadsheetApp.create("Merged Sheets");
/* Iterate over the spreadsheets over the folder */
while(spreadSheets.hasNext()) {
var sheet = spreadSheets.next();
/* Open the spreadsheet */
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
/* Get all its sheets */
for(var y in spreadSheet.getSheets()) {
/* Copy the sheet to the new merged Spread Sheet */
spreadSheet.getSheets()[y].copyTo(newSpreadSheet);
}
}
}
答案 0 :(得分:0)
你可以做的是将提取的文件的结果(你的while循环)存储在一个数组中,然后对数组进行排序,最后附加在数组中排序的工作表(因为数组的值是有序的)
这里你的代码重新考虑了我的想法(没有测试过,所以可能有一些错误)
function mergeSheets() {
/* Retrieve the desired folder */
var myFolder = DriveApp.getFoldersByName(SOURCE).next();
/* Get all spreadsheets that resided on that folder */
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
/* Create the new spreadsheet that you store other sheets */
var newSpreadSheet = SpreadsheetApp.create("Merged Sheets");
/* Iterate over the spreadsheets over the folder */
var spreadsheetsList = [];
while(spreadSheets.hasNext()) {
var sheet = spreadSheets.next();
spreadsheetsList.push([sheet.getName(),sheet.getId()]);
}
spreadsheetsList.sort(function(a,b){return a[0].localCompare(b[0])});
for(var i =0; i< spreadsheetsList.length; i++){
/* Open the spreadsheet */
var spreadSheet = SpreadsheetApp.openById(spreadsheetsList[i][1]);
/* Get all its sheets */
for(var y in spreadSheet.getSheets()) {
/* Copy the sheet to the new merged Spread Sheet */
spreadSheet.getSheets()[y].copyTo(newSpreadSheet);
}
}
}