简体   繁体   English

Google App Script 中类似 SQL 的查询功能可从 Google 表格中提取数据

[英]SQL like query features in Google App Script to pull data from Google Sheets

I am trying to build a Google Apps Script web app that will pull data from a Google sheet and display it in rows and columns in an HTML page in the browser.我正在尝试构建一个 Google Apps Script Web 应用程序,它将从 Google 工作表中提取数据并在浏览器的 HTML 页面中以行和列的形式显示它。

By following the samples etc I wrote this code that WORKS!通过遵循示例等,我编写了这段有效的代码!

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

function getData(){

var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';
var rangeName = 'Payments!A:D';

var values = Sheets
             .Spreadsheets
             .Values
             .get(spreadsheetId,rangeName)
             .values;
return values;

}

the data lying in columns A,B,C,D is getting pulled and being displayed correctly through the following HTML template位于 A、B、C、D 列中的数据被拉取并通过以下 HTML 模板正确显示

<? var data = getData(); ?>
    <table>
      <? for (var i = 0; i < data.length; i++) { ?>
        <tr>
          <? for (var j = 0; j < data[i].length; j++) { ?>
            <td><?= data[i][j] ?></td>
          <? } ?>
        </tr>
      <? } ?>
    </table>

Instead of getting all the rows and all the columns from A,B,C,DI would like to run an SQL Query to retrieve some of the columns with a WHERE clause like SQL. DI 不想从 A、B、C 中获取所有行和所有列,而是希望运行 SQL 查询以使用 SQL 之类的 WHERE 子句检索某些列。 I understand that the =QUERY() function that works in the spreadsheet does not work inside the GAS.我知道在电子表格中工作的 =QUERY() 函数在 GAS 中不起作用。 So my next attempt was to retrieve SOME of the rows by using a getBatch method .. and this is where I get ERRORs所以我的下一次尝试是使用 getBatch 方法检索一些行..这就是我得到错误的地方

in this case, i want to exclude column C and get only A,B and D,E the code that throws an error is as follows :在这种情况下,我想排除 C 列并仅获取 A、B 和 D、E 引发错误的代码如下:

function getData2(){

var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';

/* var rangeName1 = 'Payments!D'; */
/* var rangeName2 = 'Payments!A'; */
var values = Sheets
             .Spreadsheets
             .Values
             .batchGet(spreadsheetId,{ranges: ['Payments!D:E', 'Payments!A:B']})
             .values;
return values;

}

In the corresponding HTML template, all that changes is getData is replaced with getData2在相应的 HTML 模板中,所有更改都是 getData 替换为 getData2

<? var data = getData2(); ?>

with this code, I get the following error :使用此代码,我收到以下错误:

TypeError: Cannot read property "length" from undefined.类型错误:无法从未定义中读取属性“长度”。 (line 6, file "Code", project "Report003") (第 6 行,文件“代码”,项目“Report003”)

Now I have two questions :现在我有两个问题:

  1. What is wrong in my code and how can i fix it?我的代码有什么问题,我该如何解决?
  2. Is it possible to use SQLite to simplify the process of extracting the desired rows and columns是否可以使用 SQLite 来简化提取所需行和列的过程

I have seen this question but I am not able to understand the answer adequately我看过这个问题,但我无法充分理解答案

I finally understood what this solution was and modified it as given below.我终于明白了这个解决方案是什么,并如下修改了它。 Now we can use any SQL that is supported by the QUERY() function.现在我们可以使用 QUERY() 函数支持的任何 SQL。

function mostSQL(){

var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';
var targetRange = 'Payments!A:G';
var SQL = 'select A, G where G >= 700 and G <= 800'
var Query = '=QUERY('+targetRange+',\"'+SQL+'\")'

var currentDoc = SpreadsheetApp.openById(spreadsheetId)
var tempSheet = currentDoc.insertSheet();

var pushQuery = tempSheet.getRange(1, 1).setFormula(Query);
var pullResult = tempSheet.getDataRange().getValues();

currentDoc.deleteSheet(tempSheet); 

return pullResult;

}

You can use Google Visualization API Query Language to perform data manipulations with the query to the data source.您可以使用Google Visualization API 查询语言通过对数据源的查询来执行数据操作。 The syntax of the query language is similar to SQL查询语言的语法类似于 SQL

code.gs代码.gs

function doGet() {
 // SpreadsheetApp.openById("SSID"); // To define the oAUTH Scope - https://www.googleapis.com/auth/spreadsheets
 var output = HtmlService.createTemplateFromFile('index');
  output.token = ScriptApp.getOAuthToken();
  return output
        .evaluate()
        .setTitle('SQL Query');
}

index.html索引.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

    <div id="dataTable"><h4>Loading...</h4></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <script>

    google.load('visualization', '1.0', {packages: ['corechart','table']});
    google.setOnLoadCallback(loadEditor);

      function loadEditor() {
        var queryString = encodeURIComponent("SELECT A,B,D,E where A!= 'JACK'");
        var SSID = "ADD YOUR SPREADSHEET"
        var SHEET_NAME = "SHEET NAME"
        var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key='+SSID+'&sheet='+SHEET_NAME+'&oauth_token=<?=ScriptApp.getOAuthToken()?>&headers=1&tq=' + queryString);
        query.send(handleSampleDataQueryResponse);
      }

      function handleSampleDataQueryResponse(response) {
        console.log(response)
        var data = response.getDataTable();
        console.log(data);
        var chartTbl = new google.visualization.Table(document.getElementById('dataTable'));
        chartTbl.draw(data);
      }

    </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM