简体   繁体   中英

General Google Apps script to display data from a Google sheet in a datatable

I hope someone can help. I've followed a tutorial to create a Google Apps Script to load data from a Google Sheet and display in a datatable. So far, I have this...

code.gs

function doGet() {
  return HtmlService
         .createTemplateFromFile('index')
         .evaluate()
         .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
 
function getData(){ // Get data from Google sheet and return as an array
  var spreadSheetId = "SPREADSHEET_ID";
  var dataRange     = "RANGE";
  var range         = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
  var values        = range.values; 
  return values;
}
 
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
         .getContent();
}

index.html

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"/>

<?!= include('javascript.html'); ?> <!-- include javascript file -->

<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
  <!-- Table data is added by the showData() function -->
</table>

javascript.html

<script>
  google.script.run.withSuccessHandler(showData).getData(); // Run the apps script
  function showData(dataArray){ // Generate the table from the data array
    $(document).ready(function(){
      $('#data-table').DataTable({
        data: dataArray,
        order: [[0,"asc"]],
        autoWidth: true,
        columns: [
          {"title":"HEADING"},
          {"title":"HEADING"},
          {"title":"HEADING"},
          {"title":"HEADING"}
        ]
      });
    });
  }
</script>

It works fine if I hard code the Spreadsheet ID, range and the column headings. How do I generalise this script to take URL parameters to allow me to specify these values?

You can pass URL parameters to a WebApp and then access them client-side with scriptlets

Those parameters will have the following syntax:

e.parameter

{"name": "alice", "n": "1"}

and for arrays:

e.parameters

{"name": ["alice"], "n": ["1", "2"]}

  • For range notation - make sure to encode or substitute : through something different (since it is not allowed in an url) and then restore it again

  • After passing the url paramters to the WebAPP, use scriptlets to pass the variables from server to client-side.

  • Then you can pass them back from client to server-side as paramters in google.script.run

You modified code for an URL type

https://script.google.com/XXXXXXX/exec?id=1gCiCPHxoY7F0XhrVXDFytMdIKMDT3jVETcHWMGAzV0M&range=A1_F5&headers=a&headers=b&headers=c

could look like this:

Code.gs

var headers = [];
var spreadSheetId = "";
var dataRange = "";

function doGet(e) {
  headers = e.parameters.headers;
  spreadSheetId = e.parameter.id;
  // colons cannot be passed as URL parameters
  dataRange = e.parameter.range.replace("_", ":");
  console.log(headers)
  console.log(spreadSheetId)
  console.log(dataRange)
  return HtmlService
         .createTemplateFromFile('index')
         .evaluate()
         .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
 
function getData(spreadSheetId, dataRange){ 
  var range = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
  var values = range.values; 
  return values;
}

index.html (including JS)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"/>
<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
  <!-- Table data is added by the showData() function -->
</table>

 <script>

// get parameters from server-side
  const headers = JSON.parse("<?=JSON.stringify(headers)?>");
  const spreadSheetId = JSON.parse("<?=JSON.stringify(spreadSheetId)?>");
  const dataRange = JSON.parse("<?=JSON.stringify(dataRange)?>");

// pass parameters to getData()
  google.script.run.withSuccessHandler(showData).getData(spreadSheetId, dataRange); 
  
  function showData(dataArray){ // Generate the table from the data array
    $(document).ready(function(){

 //build your column object dynamically
    var columns = [];
    headers.forEach(function(header){
    columns.push({"title":header})
    })
      $('#data-table').DataTable({
        data: dataArray,
        order: [[0,"asc"]],
        autoWidth: true,
        columns: columns
      });
    });
  }
</script>
  </body>
</html>

NOTE:

An alternative to passing spreadsheetId form server to client and back, would be store them in script properties which would be accessiable both from goGet() (to write) and getData() (to read).

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