简体   繁体   English

用于在数据表中显示来自 Google 工作表的数据的通用 Google Apps 脚本

[英]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.我已经按照教程创建了一个 Google Apps 脚本,以从 Google 表格加载数据并显示在数据表中。 So far, I have this...到目前为止,我有这个...

code.gs代码.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索引.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 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.如果我对电子表格 ID、范围和列标题进行硬编码,它就可以正常工作。 How do I generalise this script to take URL parameters to allow me to specify these values?如何概括此脚本以获取 URL 参数以允许我指定这些值?

You can pass URL parameters to a WebApp and then access them client-side with scriptlets您可以将URL 参数传递给 WebApp,然后使用 scriptlet 在客户端访问它们

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对于范围表示法 - 确保编码或替换:通过不同的东西(因为它在 url 中是不允许的),然后再次恢复它

  • After passing the url paramters to the WebAPP, use scriptlets to pass the variables from server to client-side.将 url 参数传递给 WebAPP 后,使用scriptlet将变量从服务器传递到客户端。

  • Then you can pass them back from client to server-side as paramters in google.script.run然后您可以将它们作为 google.script.run 中的参数从客户端传递回服务器端

You modified code for an URL type您修改了 URL 类型的代码

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

could look like this:看起来像这样:

Code.gs代码.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) index.html(包括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).将电子表格 ID 表单服务器传递给客户端并返回的替代方法是将它们存储在 脚本属性中,这些 属性可以从goGet() (写入)和getData() (读取)访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 需要从 Google Apps 脚本查询 Google 表格以获取特定数据 - Need to Query Google Sheet for specific data from Google Apps Script Google 表格 - 使用 Apps 脚本显示参考表格中的注释 - Google Sheets - Display Note From Reference Sheet Using Apps Script 从Google Apps脚本查询Google表格 - Query a Google Sheet from Google Apps Script 我可以使用 Google Apps Script 使 Google 表单显示 Google 表格中的随机文本吗? - Can I use Google Apps Script to make a Google Form display randomized text from a Google Sheet? 使用 Google Apps 脚本将 kmz 中的数据写入工作表 - Write data from kmz on sheet with Google Apps Script 如何使用Apps脚本从Google表格中获取数据? - How to fetch data from google sheet using Apps script? Google Apps脚本从导入的包中获取有限制的工作表数据 - Google Apps Script get bounded sheet data from imported package Google Apps 脚本 - 有条件地将数据从其他 Google 表格检索到概览表格 - Google Apps Script - Conditionally retrieve data from other Google Sheet to Overview sheet 如何通过 GOOGLE APPS SCRIPT 自动将多个谷歌表格中的数据合并到另一个谷歌表格 - How to automatic combine data from multiple google sheets to another google sheet by GOOGLE APPS SCRIPT 使用唯一标识符通过Google Apps脚本根据另一个工作表中的数据更新第一工作表中的数据 - Update data in 1st sheet based on data from another sheet with google apps script via unique identifier
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM