Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data into a specific row number (or the first empty row)?

I'm using this super-handy script to get Google PageSpeed Insights metrics into a Google spreadsheet (thanks to the author):

var pageSpeedApiKey = 'AIzaSyDRgiUgu9Y3xVur0Xf0TdUmxgOYfltLFW4';
var pageSpeedMonitorUrl = 'http://www.sauder.ubc.ca';

function monitor() {
  var mobile = callPageSpeed('mobile');
  var desktop = callPageSpeed('desktop');
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName('GooglePageSpeedInsightsData');
  sheet.appendRow([
                   Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd'),
                   mobile.score,
                   desktop.score
                  ]);

    // more available, i.e. desktop.pageStats.numberResources
}

function callPageSpeed(strategy) {
  var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=' + pageSpeedMonitorUrl + '&key=' + pageSpeedApiKey + '&strategy=' + strategy;
  var response = UrlFetchApp.fetch(pageSpeedUrl);
  var json = response.getContentText();
  return JSON.parse(json);
}

I'm using another script that adds a blank row on row 3 to my sheets to keep all my data in reverse chronological order as new data comes in.

So instead of appending to the last row, I need it inserted into "row 3", or to "the first empty row"!

like image 463
Drewdavid Avatar asked Feb 24 '17 23:02

Drewdavid


1 Answers

You can insert a new row at row 3, and then get the range for row 3 and set the values:

sheet.insertRows(3, 1);//shift all rows down by one from row 3

sheet.getRange(3,1,1,3)//(start row, start column, number of rows, number of columns
   .setValues([[
               Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd'),
               mobile.score,
               desktop.score
              ]]);

Apps Script Documentation for insertRows()

like image 192
Alan Wells Avatar answered Sep 30 '22 00:09

Alan Wells