您可以在數組級別進行排序,只需從工作表中獲取數據到矩陣中,然後選擇要排序的列進行多次排序。
是這樣的:
function test(){
sortSheetOnColumn(2,3)
}
function sortSheetOnColumn(col1,col2){
var sh = SpreadsheetApp.getActiveSheet();
var data = sh.getDataRange().getValues();// get all data
var header = data.shift();
data.sort(function(x,y){ // Note: sort method changes the original array
// var xp = Number(x[col2-1]);// use these to sort on numeric values
// var yp = Number(y[col2-1]);
var xp = x[col2-1].toLowerCase();// use these for non-numeric values
var yp = y[col2-1].toLowerCase(); // I used toLowerCase() for my use case but you can remove it or change it to whatever you need
Logger.log(xp+' '+yp); // just to check the sort is OK
return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col ascending
});
data.sort(function(x,y){ // Note: sort method changes the original array
// var xp = Number(x[col1-1]);// use these to sort on numeric values
// var yp = Number(y[col1-1]);
var xp = x[col1-1].toLowerCase();// use these for non-numeric values
var yp = y[col1-1].toLowerCase();//
Logger.log(xp+' '+yp); // just to check the sort is OK
return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col ascending
});
// and at the end take back the headers
data.unshift(header);
sh.getDataRange().setValues(data);
}
或更好,下面亞當的評論:
function sortSheetOnColumn2(col1, col2) {
var sh = SpreadsheetApp.getActiveSheet();
var data = sh.getDataRange().getValues();// get all data
var header = data.shift(), x1, y1, x2, y2;
col1--;
col2--;
data.sort(function(x, y) {
x1 = x[col1].toLowerCase();
y1 = y[col1].toLowerCase();
x2 = x[col2].toLowerCase();
y2 = y[col2].toLowerCase();
return x1 == y1 ? (x2 == y2 ? 0 : x2 < y2 ? -1 : 1) : x1 < y1 ? -1 : 1;
});
data.unshift(header);
sh.getDataRange().setValues(data);
}
但邁克爾的,如果更聰明在Range.sort方法使用建立一個我不知道的答案(至少是其擴展的可能性)。
這是一流的解決方案!我不知道那種方法。感謝您的信息:-) – 2013-04-07 13:50:02
非常感謝,這正是我一直在尋找的。 – 2013-04-07 14:34:52
新文檔包含豐富的新信息和代碼示例,值得一看。感謝Google員工。 – ScampMichael 2013-04-07 14:55:36