从电子表格获取所有数据到html

时间:2018-11-01 23:55:19

标签: html google-apps-script web-applications google-sheets

当我将其作为Google脚本(在code.gs内)运行时,它可以工作,但是,当我将其带入index.html文件时,无法从电子表格中获取全部数据。

工作表应为3D,sheets[0]应显示工作表0(行x列)中的所有数据 但是相反,在data中,我得到了看起来像字符串的字符串(当我执行data[0]时,它仅显示第一个字符)。为什么?

代码如下:

GAS

function doGet(request) {
  return HtmlService.createTemplateFromFile('index')
    .evaluate();
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
    .getContent();
}

function getSheetsData(){
  ss = SpreadsheetApp.openById('id_key');         
  var sheets = []; 
  for (var i = 0; i < ss.getSheets().length; ++i) {           
    sheets.push(ss.getSheets()[i].getDataRange().getDisplayValues());  
  }    
  return (sheets)
}

客户侧

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">    
    <?!= include('css'); ?>    

    <!-- the idea is to pull the data from the spreadsheet and build slides with the questions to show a Quiz of questions (not yet done)-->
    <script>
      var datas = null;
      google.script.run.withSuccessHandler(function(result){ 
        datas = result;
        console.log(datas); //YES, datas has the data
      }).getSheetsData();
      console.log(datas);   //NO, datas is null
    </script>         
    </head>

  <body>    
  <h1>TESTS QUIZ [WEB APP]
    <br>
    <br>
      <!-- Build select options from spreadsheet sheets -->
      <?  var ss = SpreadsheetApp.openById('id_key'); ?>
      <select class="classic" id="sheet" onchange="someFunctionWillGoHereToStartTheQuiz">
      <option value="" disabled selected style="display:none;">Choose Quiz</option>
      <? for (var i = 0; i < ss.getSheets().length; ++i) { ?>      
        <option value="<?=i?>"><?= ss.getSheets()[i].getSheetName() ?></option>   
      <? } ?>
      </select>  
      <br>
      <br>
  </h1>
  <!--some code will go here to show the questions in the page-->

1 个答案:

答案 0 :(得分:1)

一个建议是使用这种方法。

  1. 在服务器端创建一个函数以获取所有数据
  2. 使用成功处理程序并调用google.script.run.myFunction()
  3. 来检索客户端的数据

GAS

function getSheetsData(){
 ss = SpreadsheetApp.openById('id_key_spreadsheet');         
    var sheets = []; //except if you want to add more datas no need to declare a 3D array
    for (var i = 0; i < ss.getSheets().length; ++i) {
       // I'v corrected this part so you don't get any "out of bounds" errors
      sheets.push(ss.getSheets()[i].getDataRange().getDisplayValues());  
    }
  return (sheets)
}

客户端

<script>
 var datas = null;
 google.script.run.withSuccessHandler(function(result)
   { 
     datas = result;
   }).getSheetsData();
</script>

现在,如果您想获取第一个字符串,请考虑使用2次[]  datas[0][0],因为您正在使用2D数组。您的问题也可能来自这里。

参考

google.script.run

相关问题