简体   繁体   中英

Adding a time stamp for data inserted into Google Sheets using Google BigQuery / Apps Script

I'm following the code sample here to insert data from BigQuery into Google Sheets using Google Apps Script.

I was able to get the script to work, but I would like to add an updated timestamp to the data as a new column.

Referring to the sample above, in this specific section:

(Original code)

  if (rows) {
    var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
    var sheet = spreadsheet.getActiveSheet();

    // Append the headers.
    var headers = queryResults.schema.fields.map(function(field) {
      return field.name;
    });
    sheet.appendRow(headers);

    // Append the results.
    var data = new Array(rows.length);
    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].f;
      data[i] = new Array(cols.length);
      for (var j = 0; j < cols.length; j++) {
        data[i][j] = cols[j].v;
      }
    }
    sheet.getRange(2, 1, rows.length, headers.length).setValues(data);

To give an example of what I am trying to achieve, say if I ran this query: select sample_data from data limit 3

Results:

sample_data
1
2
3

I would like to add an additional column of data with the current timestamp. I can do this by: select sample_number, current_timestamp() as now from data

sample_number   now
1               2021-07-29 06:19:04.291269 UTC
2               2021-07-29 06:19:04.291269 UTC
3               2021-07-29 06:19:04.291269 UTC

But I would like to achieve this result using Google Apps Script, so that I don't need to append current_timestamp() as now to all SQL queries that would be called using this module.

I was thinking something along the lines of:

sheet.getRange(2, 1, rows.length, headers.length + 1).setvalues(new Date());

However, I think it would be a column length mismatch.

I'm thinking I would need to add a new column to the array, then add new Date() as row values, before calling .setValues() to write the array to Google Sheets, but not sure how to do it.

Can anyone help me out?

setValues(values) requires an Object[][] .

You should add the 'date column' to your data array and then setValues

const date = new Date();
for (let i = 0; i < data.length; i++) {
  if (i === 0) { row.push('now'); }
  else { row.push(date); }
}
sheet.getRange(2, 1, data.length, data[0].length).setValues(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM