表格上的自动排序

时间:2016-02-22 20:55:55

标签: sorting google-apps-script google-sheets

我试图弄清楚如何自动按字母顺序对表单进行排序。每当我在A-C列下添加一个新条目时,我希望它能自动与其他数据一起排序。

我听说必须使用Google应用脚本完成此操作。任何人都可以帮我吗?

提前致谢!

https://docs.google.com/spreadsheets/d/1XH4mrKa6W4se5WwM6oKqh959gG2kAQVtAmOnml13VoE/edit#gid=0

2 个答案:

答案 0 :(得分:21)

电子表格很容易从脚本中排序,脚本很容易被电子表格“事件”触发。

onEdit是适合您需求的其中一项活动。 Doc herehere

然后排序过程是shown in the doc,我重现下面的代码:

var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];
 var range = sheet.getRange("A1:C7");

 // Sorts by the values in the first column (A)
 range.sort(1);

 // Sorts by the values in the second column (B)
 range.sort(2);

 // Sorts descending by column B
 range.sort({column: 2, ascending: false});

 // Sorts descending by column B, then ascending by column A
 // Note the use of an array
 range.sort([{column: 2, ascending: false}, {column: 1, ascending: true}]);

 // For rows that are sorted in ascending order, the "ascending" parameter is
 // optional, and just an integer with the column can be used instead. Note that
 // in general, keeping the sort specification consistent results in more readable
 // code. We could have expressed the earlier sort as:
 range.sort([{column: 2, ascending: false}, 1]);

 // Alternatively, if we wanted all columns to be in ascending order, we would use
 // the following (this would make column 2 ascending)
 range.sort([2, 1]);
 // ... which is equivalent to
 range.sort([{column: 2, ascending: true}, {column: 1, ascending: true}]);

答案 1 :(得分:-1)

您还可以创建函数并按列名排序。调用函数时,请将列名称作为字符串输入。

<div id="container" style="width: 75%;">
    <canvas id="canvas"></canvas>
</div>
<script>
var lineChartData = {
        labels : ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
        datasets : [
            {
                type: 'line',
                label: "2017",
                backgroundColor: 'rgba(151,249,190,0.5)',
                borderColor: 'rgba(151,249,190,1)',
                borderWidth: 1,
                data : [1,2,3,4,5,6,7,8,9,10,11,12],
                fill: true
            },
            {
                type: 'line',
                label: "2018",
                backgroundColor: 'rgba(252,147,65,0.5)',
                borderColor: 'rgba(252,147,65,1)',
                borderWidth: 1,
                data : [12,11,10,9,8,7,6,5,4,3,2,1],
                fill: true
            }
        ]
    };
window.onload = function() {
    var ctx = document.getElementById('canvas').getContext('2d');
    window.myBar = new Chart(ctx, {
        type: 'line',
        data: lineChartData,
        options: {
            responsive: true,
            legend: {
                position: 'top',
            },
            title: {
                display: true,
                text: 'Chart'
            }
        }
    });
};
</script>