首页 > 解决方案 > 使用 Apps 脚本将 HTML 表格(用户输入)更新到 Google 表格

问题描述

我正在尝试将 HTML 表(用户输入)附加到 Google 表格。我读了这篇文章,但解决方案对我不起作用。我在 Apps Script 中启用了 Google Sheets API。我可以使用 appendrow 来更新每次单击的每一行,但我期待通过单击来附加整个表。

HTML 前端。

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <table id="t01">
  <tr>
    <th>Project</th>
    <th>Current Light Type</th>
    <th>Qty</th>
  </tr>
  <tr>
    <td><input type="text" id="p1" size="25"></td>
    <td>      
       <select id="l1">
         <option>2D</option>
         <option>Donwlight</option>
       </select>
    </td>
    <td><input type="text" id="q1" size="25"></td>
  </tr>
  <tr>
    <td><input type="text" id="p2" size="25"></td>
    <td>
      <select id="l2">
        <option>2D</option>
        <option>Donwlight</option>
       </select>
    </td>
    <td><input type="text" id="q2" size="25"></td>
  </tr>
  </table> 
    <div>
    <button id="btn">Submit</button>
    </div>
      <script>
      document.getElementById("btn").addEventListener("click",parse_to_backend);
      function parse_to_backend(){
        let table = document.getElementById("t01").outerHTML;
        google.script.run.pasteHtml(table);
        document.getElementById("p1").value="";
        document.getElementById("l1").value="";
        document.getElementById("q1").value="";
       };
       </script>
  </body>
</html>

JS 后端

function doGet(e) {
  return HtmlService.createTemplateFromFile("page").evaluate();
}

function pasteHtml(table) {
  var url = "https://docs.google.com/spreadsheets/d...";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Data");
  var req = {
    requests: [
      {
        pasteData: {
          html: true,
          data: table,
          coordinate: {
            sheetId: ws,
            rowIndex: 0,
            columnIndex: 0,
          },
        },
      },
    ],
  };
  Sheets.Spreadsheets.batchUpdate(req, ws);
}

标签: google-apps-script

解决方案


你很近。从您引用的答案中,您没有维护两件关键的事情。

  1. 的值sheetId需要是工作表的 ID,而不是工作表ws
  2. Sheets.Spreadsheets.batchUpdate()调用需要电子表格 ID,而不是电子表格本身。
function pasteHtml(table) {
  var url = "https://docs.google.com/spreadsheets/d...";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Data");
  var req = {
    requests: [
      {
        pasteData: {
          html: true,
          data: table,
          coordinate: {
            sheetId: ws.getSheetId(), // Pass the sheet ID
            rowIndex: 0,
            columnIndex: 0,
          },
        },
      },
    ],
  };
  Sheets.Spreadsheets.batchUpdate(req, ss.getId());  // Pass the spreadsheet ID
}

现在,由于您在前端代码中提取表格的方式(因为它实际上是表格中的输入),您将遇到一些其他问题,但这有效。如果您对如何提取表格/输入数据有其他问题,请发布另一个问题并添加 javascript 标签,以便其他人可以帮助您。

在此处输入图像描述


推荐阅读