Google apps script AppendRow to the top

后端 未结 1 1881
Happy的楠姐
Happy的楠姐 2021-02-09 03:36

As I know

appendRow(rowContents) add values to the bottom of the spreadsheet But how to add data from form in multiple rows in top of spreadsheet?

相关标签:
1条回答
  • 2021-02-09 04:10

    There's no single function to do this, but it's not that difficult write one. Here's an example:

    function prependRow(sheet, rowData) {
      sheet.insertRowBefore(1).getRange(1, 1, 1, rowData.length).setValues([rowData]);
    }
    

    I would actually allow for an optional index, let's say we want to insert after the 2nd row, skipping the header.

    function insertRow(sheet, rowData, optIndex) {
      var index = optIndex || 1;
      sheet.insertRowBefore(index).getRange(index, 1, 1, rowData.length).setValues([rowData]);
    }
    

    But appendRow also has another interesting characteristic, it's concurrent-safe. Which means it can be triggered multiple times in parallel and won't mess up. To make our function concurrent safe you have to lock it, like this:

    function insertRow(sheet, rowData, optIndex) {
      var lock = LockService.getScriptLock();
      lock.waitLock(30000);
      try { 
        var index = optIndex || 1;
        sheet.insertRowBefore(index).getRange(index, 1, 1, rowData.length).setValues([rowData]);
        SpreadsheetApp.flush();
      } finally {
        lock.releaseLock();
      }
    }
    

    Then, to use it in your code just call..

    function getValuesFromForm(form){
      //...
      insertRow(sheet, [order,lastName,firstName]); //could have passed an extra `2` parameter to skip a one line header
    }
    
    0 讨论(0)
提交回复
热议问题