Using google-apps-script from google-spreadsheet, I'm trying to fetch some hundreds of rows of data using fetchUrl and paste them into my sheet using sheet.appendRow.
Fetching data and splitting to arrays are OK. But appending them to a sheet row by row ocasionally fails without any errors and resulting in empty rows.
Here's quite simple example to recreate the problem.
function appendTest() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
sheet = SpreadsheetApp.setActiveSheet(sSheet.getSheets()[2]);
for (var i = 0; i <= 100; i++) {
sheet.appendRow([i, 1, 2, 3, 4, 5]);
}
}
About 5 or 10 rows, differs time to time, become empty. Inserting Utilities.sleep() seems to be not working, either.
Does anybody have any idea to get rid of this situation? Thank you in advance.
You could try to use batch writing to the sheet like this
function appendTest() {
var target = new Array()
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
sheet = SpreadsheetApp.setActiveSheet(sSheet.getSheets()[2]);
for (var i = 0; i <= 100; i++) {
target.push(['some data','in some columns','bla bla']);
}
sheet.getRange(sSheet.getLastRow()+1,1,target.length,target[0].length).setValues(target);
}
Note that if you think the sheet will be too 'short' you could append empty rows in the loop as well.
EDIT : following Michael pertinent answer, it would be a much better idea to add the necessary rows using sheet.insertRowsAfter(sheet.getMaxRows(), target.length)
Using appendRow inside a loop is flaky and not best practice. Please see:
https://productforums.google.com/forum/#!topic/docs/y0E9PB_VTJw
for a discussion of this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With