Copy/Push data from array into a sheet range one row at a time using Google Apps Script

前端 未结 1 1308
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 18:50

I\'ve a multi-dimensional array sheetValues[][] created using .getValues() on the origination sheet. I\'d like to copy the values from the sheetValues array into the destination

1条回答
  •  被撕碎了的回忆
    2021-01-23 19:36

    Never 'push each row of the array, one at a time". This is clunky code and extremely slow to boot. Setting values it very similar to getting values. You declare a range variable with appropriates coordinates that fit the dimensions of your values[][] array, and pass the entire values array to 'setValues()' method of the Range object.

    One of method signatures for getRange() is the following:

    sheet.getRange(row, column, numberOfRows, numberOfColumns);
    

    More info https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow-column-numrows-numcolumns

    The first 2 arguments are for the upper leftmost cell in a range while others define the number of rows and columns your range should span.

    Presuming you'd like to start inserting values from the 1st cell in the target sheet, here's the single line of code that you need.

    sheet.getRange(1, 1, sheetValues.length, sheetValues[0].length);
    

    The number of rows is the length of your array, the number of columns is the length of the first element(row) of the array.

    UPDATE

    I missed the comment buried in your code. You can filter values before writing them to the target sheet.

    sheetValues = sheetValues.map(function(row){
    
    if (row[9] == 'Target') { return row;  }
    
    });
    

    0 讨论(0)
提交回复
热议问题