从 Google 工作表中提取数据并显示在 HTML H3 标签中

Pull Data from Google Sheets and display in HTML H3 tag

我正在尝试从 Google 工作表中提取数据并显示在具有特定 ID 的 H3 标签中。这是我的 Google Sheet 的 link。我只想从 sheet 中提取价格并显示在 H3 标签中。我怎样才能做到这一点?

Code.gs

function doGet() {
var temp = HtmlService.createTemplateFromFile('index');
temp.list = getValues();
return temp.evaluate();
}

function getValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName('Sheet1');
var lastRow = ws.getLastRow();
var numRow = lastRow - 1;
return ws.getRange(2,1,numRow,2).getValues();
}

HTML

    <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>50-74 gallons: </h1><h3 id="firstPrice"></h3>
    <h1>74-99 gallons: </h1><h3 id="secondPrice"></h3>
    <h1>100-124 gallons: </h1><h3 id="thirdPrice"></h3>
  </body>
</html>

因为模板变量 (list) 中已经有 sheet 值,遍历该变量,考虑到它是一个二维数组并且每个内部数组都有两个元素,对应于GallonsPrice:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <? for(var i=0; i<list.length; i++){ ?>
      <h1><?= list[i][0] ?></h1>
      <h3 id=<?= `price_${i+1}` ?>><?= list[i][1] ?></h3>
    <? } ?>
  </body>
</html>

如果您希望每个 h3 都有一个 id 代表索引(如您所写的 firstPrice),您可以将循环索引添加到每个 id,例如上面的代码片段所示:

id=<?= `price_${i+1}` ?>

重要提示:

请注意,这仅适用于 Apps Script web apps. The syntax <?= ?> is specifically designed for Apps Script, and will not work if you try it in another environment. See scriptlets

编辑:

如果您不想使用循环,而是手动编写 HTML 元素,您可以这样做:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1><?= list[0][0] ?></h1><h3 id="firstPrice"><?= list[0][1] ?></h3>
    <h1><?= list[1][0] ?></h1><h3 id="secondPrice"><?= list[1][1] ?></h3>
    <h1><?= list[2][0] ?></h1><h3 id="thirdPrice"><?= list[2][1] ?></h3>
  </body>
</html>