Reading Google Sheets Data using JavaScript and Google Sheets API Tutorial

In this tutorial, we will tackle about Reading Google Spreadsheets Data using JavaScript and Google Sheets API. The tutorial aims to provide the IT/CS students and new programmers a reference for learning to integrate their web applications with Google APIs specifically using Google Sheets and JavaScript. Here, a step-by-step tutorial with snippets is provided and a sample web application source code file that demonstrates the said integration is also provided and free to download.

What is Google Sheets API?

The What is Google Sheets API is a RESTful API implemented by Google to allow developers to integrate Google Sheets into their web application projects. Developers use this API to create, read, and modify spreadsheets using their applications.

How to use Google Sheet API?

Here are the following steps to setup Google Sheets API in Google to use it for your web applications

  1. Browse the Google Developers Console page in your preferred browser.
  2. Create a new project in Google Developers Console and fill in the required fields.

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

  3. After the successful creation of the Project, select your created project and go to its Dashboard.

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

  4. On the search box located at the top center of the screen, enter "Google Sheets API" find the Google Sheets API on the suggestion box and click it.

    Google Developers Console - Google Sheets API Steps

  5. Enable the Google Sheets API

    Google Developers Console - Google Sheets API Steps

  6. On the side navigation menu, click the APIs & Services menu and create an OAuth consent screen. Kindly fill in the required fields on the form like the images shown below.

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

  7. On the Credentials page, create an API Key

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

  8. On the Credentials page, create an OAuth Client ID. Kindly fill in the required fields on the form.

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

    Google Developers Console - Google Sheets API Steps

How to use Read Google Sheet Data using JavaScript and Google API?

In order to read the Google Sheet Data using Google API and JavaScript, we will use the generated Client ID and API Key.

Here are the simple snippets of reading Google Sheets data using JavaScript and Google Sheets API.

Interface

The below snippet is the script for the web application's main page. It contains the Authorization/Sign-in and Sign-out Button for reading the spreadsheets data.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Google Sheets API | JavaScript</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  11.     <style>
  12.         html, body{
  13.             min-height:100%;
  14.             width:100%;
  15.         }
  16.         .table-holder{
  17.             width:100%;
  18.             max-height:65vh;
  19.             overflow:auto;
  20.         }
  21.         .table>thead{
  22.             position:sticky;
  23.             top:0;
  24.             background:white;
  25.             z-index: 1;
  26.         }
  27.     </style>
  28. </head>
  29.     <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  30.         <div class="container">
  31.             <a class="navbar-brand" href="./">Google Sheets API</a>
  32.             <div>
  33.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  34.             </div>
  35.         </div>
  36.     </nav>
  37.     <div class="container-fluid px-5 my-3" id="SampleApp">
  38.         <div class="col-lg-6 col-md-10 col-sm-12 mx-auto">
  39.             <h3 class="text-center"><b>Reading Google Sheets using Google Sheets API and JavaScript</b></h3>
  40.             <div class="d-flex w-100 justify-content-center">
  41.                 <hr class="w-50">
  42.             </div>
  43.             <div class="d-flex w-100 justify-content-between mb-3">
  44.                 <div class="col-lg-3 col-md-4 col-sm-6">
  45.                     <button id="signin_btn" class="btn btn-sm btn-block w-100 btn-primary rounded-pill" type="button" onclick="GAuth()">Sign In</button>
  46.                 </div>
  47.                 <div class="col-lg-3 col-md-4 col-sm-6">
  48.                     <button id="signout_btn" class="btn btn-sm btn-block w-100 btn-danger rounded-pill" type="button" onclick="GAuthSignout()">Sign Out</button>
  49.                 </div>
  50.             </div>
  51.             <div class="card rounded-0 shadow" id="dataSheetCard">
  52.                 <div class="card-header rounded-0">
  53.                     <div class="d-flex w-100 justify-content-between">
  54.                         <div class="col-auto flex-shrink-1 flex-grow-1">
  55.                             <div class="card-title">Sample Data Sheet Data</div>
  56.                         </div>
  57.                         <div class="col-auto flex-shrink-1">
  58.                             <button class="btn btn-primary btn-sm rounded-0" type="button" onclick="ReloadDataSheet()">Reload Data</button>
  59.                         </div>
  60.                     </div>
  61.                 </div>
  62.                 <div class="card-body rounded-0">
  63.                     <div class="container-fluid">
  64.                         <div class="table-holder">
  65.                             <table class="table table-stripped table-bordered table-hover" id="contentTable"></table>
  66.                         </div>
  67.                         <div class="alert alert-danger" style="display:none" id="err_msg"></div>
  68.                     </div>
  69.                 </div>
  70.             </div>
  71.         </div>
  72.     </div>
  73.     <script async defer src="https://apis.google.com/js/api.js" onload="GAPILoaded()"></script>
  74.     <script async defer src="https://accounts.google.com/gsi/client" onload="GSILoaded()"></script>
  75.     <script src="app.js"></script>
  76. </body>
  77. </html>

Note: Please make sure that the following external scripts are loaded on the interface script.

  1. <script async defer src="https://apis.google.com/js/api.js" onload="GAPILoaded()"></script>
  2. <script async defer src="https://accounts.google.com/gsi/client" onload="GSILoaded()"></script>

The app.js script that is loaded with the main page interface is the file that contains the JavaScript codes for integrating the Google Sheet with the application.

JavaScript

Here's the snippet that is written in the app.js. The following code contains the scripts for initiating the Google Authentication/Consent and Google API.

  1. // App Credentials
  2. const client_id = '{client-id}'; // Replace the vakue with your Google API Client ID
  3. const api_key = '{api-key}'; // Replace the vakue with your Google API key
  4.  
  5. // Discovery doc URL for APIs used by the quickstart
  6. const DISCOVERY_DOC = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
  7.  
  8. // Authorization scopes required by the API; multiple scopes can be
  9. // included, separated by spaces.
  10. const SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly';
  11.  
  12. let ClientToken;
  13. let GAPI_init = false;
  14. let GIS_init = false;
  15.  
  16. const dataSheetCard = document.getElementById('dataSheetCard')
  17. const signin_btn = document.getElementById('signin_btn')
  18. const signout_btn = document.getElementById('signout_btn')
  19.  
  20. signin_btn.style.display = 'none'
  21. signout_btn.style.display = 'none'
  22. dataSheetCard.style.display = 'none'
  23.  
  24. /**
  25. * Callback after the API client is loaded. Loads the
  26. * discovery doc to initialize the API.
  27. */
  28. async function intializeGapiClient() {
  29.     await gapi.client.init({
  30.         apiKey: api_key,
  31.         discoveryDocs: [DISCOVERY_DOC],
  32.     });
  33.     GAPI_init = true;
  34.     enableButtons();
  35. }
  36.  
  37. /**
  38.     * Enables user interaction after all libraries are loaded.
  39.     */
  40. function enableButtons() {
  41.     if (GAPI_init && GIS_init) {
  42.         signin_btn.style.display = 'block'
  43.     }
  44. }
  45.  
  46. function GAPILoaded() {
  47.     gapi.load('client', intializeGapiClient);
  48. }
  49.  
  50.  
  51. /**
  52.     * Callback after Google Identity Services are loaded.
  53.     */
  54. function GSILoaded() {
  55.     ClientToken = google.accounts.oauth2.initTokenClient({
  56.         client_id: client_id,
  57.         scope: SCOPES,
  58.         callback: '', // defined later
  59.     });
  60.     GIS_init = true;
  61.     enableButtons();
  62. }
  63.  
  64.  
  65.  
  66. /**
  67.     *  Sign in the user upon button click.
  68.     */
  69. function GAuth() {
  70.     ClientToken.callback = async (resp) => {
  71.         if (resp.error !== undefined) {
  72.             throw (resp);
  73.         }
  74.         signout_btn.style.display = 'block';
  75.         signin_btn.innerText = 'Refresh Authorization';
  76.         dataSheetCard.style.display = 'block'
  77.         // await listMajors();
  78.         await displaySheetData();
  79.     };
  80.  
  81.     if (gapi.client.getToken() === null) {
  82.         // Prompt the user to select a Google Account and ask for consent to share their data
  83.         // when establishing a new session.
  84.         ClientToken.requestAccessToken({ prompt: 'consent' });
  85.     } else {
  86.         // Skip display of account chooser and consent dialog for an existing session.
  87.         ClientToken.requestAccessToken({ prompt: '' });
  88.     }
  89. }
  90.  
  91.  
  92. /**
  93.     * Display some content of spreedsheet
  94.     * https://docs.google.com/spreadsheets/d/1E3674wpJdfrCS1uEu7sHu3ALHciDnsBFQlEdx-XdknU/edit
  95.     */
  96. async function displaySheetData() {
  97.     let response;
  98.     try {
  99.         // Fetch first 10 files
  100.         response = await gapi.client.sheets.spreadsheets.values.get({
  101.             spreadsheetId: '1E3674wpJdfrCS1uEu7sHu3ALHciDnsBFQlEdx-XdknU',
  102.             range: 'Employee Leave Credits!A1:E',
  103.         });
  104.     } catch (err) {
  105.         console.log(err)
  106.         document.getElementById('err_msg').innerText = err.message;
  107.         document.getElementById('err_msg').style.display = 'block'
  108.         return;
  109.     }
  110.     const range = response.result;
  111.     if (!range || !range.values || range.values.length == 0) {
  112.         document.getElementById('err_msg').innerText = 'No values found.';
  113.         document.getElementById('err_msg').style.display = 'block'
  114.         return;
  115.     }
  116.  
  117.     document.getElementById('contentTable').innerHTML = '';
  118.     var tr = document.createElement('tr')
  119.     /**
  120.         * Table Header
  121.         */
  122.     var thead = document.createElement('thead')
  123.  
  124.     if (!!range.values[0]) {
  125.         var head_tr = tr.cloneNode(true)
  126.         Object.keys(range.values[0]).map(k => {
  127.             var column = range.values[0][k]
  128.             head_tr.innerHTML += `<th>${column}</th>`;
  129.         })
  130.         thead.appendChild(head_tr)
  131.         document.getElementById('contentTable').appendChild(thead)
  132.     }
  133.  
  134.     /**
  135.         * Table body
  136.         */
  137.     var tbody = document.createElement('tbody')
  138.  
  139.     Object.keys(range.values).map(k => {
  140.         if (k != 0) {
  141.             var body_tr = tr.cloneNode(true)
  142.             var rows = range.values[k]
  143.             rows.map(column => {
  144.                 body_tr.innerHTML += `<td>${column}</td>`;
  145.             })
  146.             tbody.appendChild(body_tr)
  147.         }
  148.     })
  149.     document.getElementById('contentTable').appendChild(tbody)
  150.  
  151. }
  152.  
  153.  
  154. /**
  155.     * Reload Data Sheed
  156.     */
  157.  
  158. function ReloadDataSheet(){
  159.     displaySheetData();
  160. }
  161.  
  162.  
  163. /**
  164.     *  Sign out the user upon button click.
  165.     */
  166. function GAuthSignout() {
  167.     token = gapi.client.getToken();
  168.     if (token !== null) {
  169.         google.accounts.oauth2.revoke(token.access_token);
  170.         gapi.client.setToken('');
  171.         signin_btn.innerText = 'Sign In';
  172.         signout_btn.style.display = 'none';
  173.         dataSheetCard.style.display = 'none'
  174.     }
  175. }

Make sure to change the client_id and api_key constants value with your created Google API credentials.

Snapshots

Here are the snapshots of the result of the snippets given above.

Getting the user's consent

Read Google Sheets Data using JavaScript

Displaying the Google Sheets Data into HTML Table

Read Google Sheets Data using JavaScript

The Source of Google Sheet Data

Read Google Sheets Data using JavaScript

That's the end of this tutorial. I have also provided the source code file that I created for this tutorial. You can download it by clicking the Download Button below this article.

I hope this Reading Google Sheets Data using JavaScript and Google Sheets API Tutorial helps you with what you are looking for and that you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment