Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.2 kB
5
Indexable
const { google } = require('googleapis');
const keys = require('./path-to-your-credentials-file.json');

const spreadsheetId = 'your-spreadsheet-id';

// Create a new JWT client using the key file downloaded from the Google Cloud Console
const client = new google.auth.JWT(
  keys.client_email,
  null,
  keys.private_key,
  ['https://www.googleapis.com/auth/spreadsheets']
);

// Authorize the client
client.authorize(function(err, tokens) {
  if (err) {
    console.log(err);
    return;
  }
  
  // Example: Add a new row
  addRow();

  // Example: Update the added row
  setTimeout(() => updateRow(), 2000);

  // Example: Delete the added row
  setTimeout(() => deleteRow(), 4000);
});

function addRow() {
  const sheets = google.sheets({ version: 'v4', auth: client });

  // Values to be added in the new row
  const values = [['John Doe', 'john.doe@example.com', '25']];

  sheets.spreadsheets.values.append({
    spreadsheetId: spreadsheetId,
    range: 'Sheet1', // Update with your sheet name
    valueInputOption: 'RAW',
    resource: {
      values: values,
    },
  }, (err, res) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log('Row added successfully:', res.data);
  });
}

function updateRow() {
  const sheets = google.sheets({ version: 'v4', auth: client });

  // Update values for the added row
  const updateValues = [['John Doe Updated', 'john.updated@example.com', '26']];

  sheets.spreadsheets.values.update({
    spreadsheetId: spreadsheetId,
    range: 'Sheet1!A2:C2', // Update with your sheet name and row range
    valueInputOption: 'RAW',
    resource: {
      values: updateValues,
    },
  }, (err, res) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log('Row updated successfully:', res.data);
  });
}

function deleteRow() {
  const sheets = google.sheets({ version: 'v4', auth: client });

  // Delete the added row
  sheets.spreadsheets.values.clear({
    spreadsheetId: spreadsheetId,
    range: 'Sheet1!A2:C2', // Update with your sheet name and row range
  }, (err, res) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log('Row deleted successfully:', res.data);
  });
}
Leave a Comment