设置使用谷歌应用脚本创建的 html 表格单元格的背景颜色

问题描述 投票:0回答:0

我使用应用程序脚本从谷歌工作表中的数据创建了一个 html 表。但是我无法设置我创建的 html 表格的背景颜色。我检索了工作表第 2 列中单元格的背景颜色,但对如何通过脚本在表中设置它感到困惑。我该怎么做?

这是我的脚本文件:

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile("BeneficiaryData");
}

function getTableData() {
  
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("sheet1");
  var data = ws.getRange(2, 1, ws.getLastRow()-1, 2).getValues();
  var i = 2;
  
  for (counter=0; counter<data.length; counter++){
    var bgColour = ws.getRange(i, 2, ws.getLastRow()-1, 2).getBackground();
    data[counter].push(bgColour)
    //Logger.log(bgColour);
    i++;  
  }
  
  return data;
}

由此我得到如下数据集。我正在检索背景颜色。

[[Name1, Status1, #20cf37], [Name2, Status2, #ffffff], [Name3, Status3, #ffffff]]

这是我的html文件,

<html>

<head>
  <base target="_top">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <div class="container">

    <div class="row">
      <div class="col s12">

        <table class="table table-striped">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Status</th>
            </tr>
          </thead>
          <tbody id="table-body">
          </tbody>
        </table>

      </div>
    </div> <!-- CLOSE ROW -->

  </div>

  <script>
    document.addEventListener("DOMContentLoaded",function(){
       google.script.run.withSuccessHandler(generateTable).getTableData();
        
    });


    function generateTable(dataArray){

      var tbody = document.getElementById("table-body");

        dataArray.forEach(function(r){

          var row = document.createElement("tr");
          var col1 = document.createElement("td");
          col1.textContent = r[0];     //argument 1
          var col2 = document.createElement("td");
          col2.textContent = r[1];     //argument 2
          col2.style.backgroundColor(r[2]);                              
          row.appendChild(col1);
          row.appendChild(col2);
          tbody.appendChild(row);
          
        });
    }

  </script>

</body>

</html>

我最后尝试的是这个

col2.style.backgroundColor(r[2]);
在 html 文件中,但它没有用。在检查如何设置背景颜色时,我发现 setBackgroundColor(color) 是我应该使用的方法。但是 setBackgroundColor 不适用于 col2.

javascript html google-apps-script google-sheets background-color
© www.soinside.com 2019 - 2024. All rights reserved.