Advertisement
pixeline

Fetch data from a Google Sheets

Dec 17th, 2021
1,326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Get spreadsheet npm package
  2. const { GoogleSpreadsheet } = require('google-spreadsheet');
  3. // Ensure you've updated this file with your client secret
  4. const clientSecret = require('./client_secret.json');
  5.  
  6. // Add your Google sheet ID here
  7. const googleSheetID = '1234567891234567898765465431';
  8.  
  9. // Instantiates the spreadsheet
  10. const sheet = new GoogleSpreadsheet(googleSheetID);
  11.  
  12. // Asynchronously get the data
  13. async function getData() {
  14.     try {
  15.         // Authenticate using the JSON file we set up earlier
  16.         await sheet.useServiceAccountAuth(clientSecret);
  17.         await sheet.loadInfo();
  18.  
  19.         // Get the first tab's data
  20.         const tab = sheet.sheetsByIndex[0];
  21.  
  22.         // Get row data
  23.         const rows = await tab.getRows();
  24.  
  25.         // Empty array for our data
  26.         let data = [];
  27.  
  28.         // If we have data
  29.         if (rows.length > 0) {
  30.             // Iterate through the array of rows
  31.             // and push the clean data from your spreadsheet
  32.             rows.forEach(row => {
  33.                 data.push(cleanData(row));
  34.             });
  35.         } else {
  36.             return false;
  37.         }
  38.  
  39.         console.log(JSON.stringify(data));
  40.  
  41.         // Return the data JSON encoded
  42.         return JSON.stringify(data);
  43.     } catch (err) {
  44.         console.log(err);
  45.         return false;
  46.     }
  47. }
  48.  
  49. // Add the data we want into an object
  50. function cleanData(data) {
  51.     return {
  52.         title: data['title'],
  53.         start: data['start'],
  54.         duration: data['totalDuration'],
  55.         end: data['end'],
  56.         organizer: data['organizer'],
  57.         participants: data['participants']
  58.     }
  59. }
  60. // Call the above method
  61. getData();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement