【问题标题】:Retrieve and update values in Google spreadsheet by row ID by using HTML form使用 HTML 表单按行 ID 检索和更新 Google 电子表格中的值
【发布时间】:2021-04-15 04:49:30
【问题描述】:

我能够使用以下列创建一个谷歌电子表格(包含在此处找到的想法): 产品 |尺寸 | uid 其中 uid 是随机生成的五个数字 ID (=RANDBETWEEN(10000;99999))。 然后我使用了以下应用程序脚本:

// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6 

function doGet(e){
  return handleResponse(e);
}

//  Enter sheet name where data is to be written below
        var SHEET_NAME = "Sheet1";

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.
  
  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);
    
    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = []; 
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}

然后,我把这个 php 文件放在一起:

<?php
if (isset($_GET['product'])) $product = $_GET['product'];
if (isset($_GET['size'])) $size = $_GET['size'];
if (isset($_GET['uid'])) $uid = $_GET['uid'];
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Submit rows</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>

Submit new row to google sheet.
<form id="test-form">
  
  <div>
    <label>product</label>
    <input type="text" name="product" value="<?php echo $product; ?>"/>
  </div>

  <div>
    <label>size</label>
    <input type="text" name="size" value="<?php echo $size; ?>"/>
  </div>
  
  <div>
    <label>UID</label>
    <input type="text" name="uid" value="<?php echo $uid; ?>"/>
  </div>

  <div>
    <button type="submit" id="submit-form">Submit form</button>
  </div>
  <div class="thanks"></div>

</form>


  <script>
        $(document).ready(function(){
          $.fn.serializeObject = function()
              {
               var o = {};
               var a = this.serializeArray();
               $.each(a, function() {
                   if (o[this.name]) {
                       if (!o[this.name].push) {
                           o[this.name] = [o[this.name]];
                       }
                       o[this.name].push(this.value || '');
                   } else {
                       o[this.name] = this.value || '';
                   }
               });
               return o;
              };
            var form = $('form#test-form'),
              url = 'https://script.google.com/macros/s/KEY/exec';
              form.submit(function(e){
                e.preventDefault();
              var jqxhr = $.ajax({
                url: url,
                method: "GET",
                dataType: "json",
                data: form.serializeObject()
              });
                $(".thanks").html("Sent to sheet.").css("font-size","2rem");
                $(".form-control").remove();
                $("#submit").remove();
              });
            });
        </script>


</body>
</html>

为什么喜欢这样?我有一个 QR 码,当它被扫描时,用户会被定向到这样的 url: htttps://samplesite.com/index.php?product=Pants&size=large&uid=12345

因此,表单字段由二维码/链接中的值预填充。提交表单,将值写入谷歌电子表格,一切都很好。

但是现在到问题部分! :) 产品上有另一个二维码,扫描后会打开如下网址:htttps://samplesite.com/edit.php?uid=12345

我想用这个表单打开另一个页面,其中列出了 uid 为 12345 的同一 google 电子表格的行值。使用 php,它可能类似于 select * from sheet_id where uid='12345' 然后定义列值,但显然没那么容易。

我做了一些搜索,有人建议使用 tabletop.js,但他们 (https://github.com/jsoma/tabletop) 不再推荐它。

  1. 如何通过唯一的行 ID 从谷歌电子表格中检索信息并将其作为值插入到 html 表单中? 我计划用这些数据填写表格,然后使用下拉菜单让用户更改(大小)值。这将我们引向第二部分...
  2. 如何按特定的行 ID 更新 google 电子表格?我希望此表单覆盖 id 为 12345 的同一行中的值。
  3. 既然我们已经在这里了:excel 的 randbetween 函数 足够好 用于此用途吗?或者你会推荐一个更大的数字/字母吗?不幸的是,过时的后端系统不允许我们像在常规数据库中那样将 uid 编号加一。

谢谢。

【问题讨论】:

    标签: javascript php excel google-apps-script google-sheets


    【解决方案1】:

    一种方法是直接在doGet() 中实现HTML 表单,并使用google.script.run.withSuccessHandler(yourClientFunction).yourServerFunction(someParam) 在HTML 表单和电子表格之间推送和拉取数据。这将自动处理身份验证。请参阅Web App demo

    或者,在您的客户端代码中使用Sheets API。您不需要doGet(),但需要处理身份验证。

    您不应使用randbetween() 创建 ID,因为最终会发生冲突。如果您只为 ID 分配五位数字并且从不检查重复项,birthday problem 几乎可以保证在前几百个 ID 之后会发生冲突。您应该使用递增计数器。如果这不可行,请使用Utilities.getUuid() 或类似名称。

    【讨论】:

    • 所以最后一部分,制作副本,是让它工作的线索。我确实设法让它工作(有一些新问题,因为 Apps Script 似乎不喜欢多个谷歌帐户)并部署它,但是 - 它是一个字符计数器。虽然很有趣,但它并没有真正回答我最初的问题:如何通过工作表行 ID 将电子表格的值转换为 html 表单,然后对其进行编辑?还是我又错过了重点?完全有可能,我是新手 :)
    • Web App Demo 展示了如何在 HTML 表单和电子表格之间推送和拉取数据,展示了一种实现解决方案来回答您的问题 1 和 2 的方法。该演示不进行查找来定位一个数据行并就地更新它,但这是一件相当简单的事情。我现在意识到您引用的 Apps 脚本代码不是您自己的 — 您可能需要查看 HTML Service 文档以了解其工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多