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

帅比萌擦擦* 提交于 2021-01-21 05:59:04

问题


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.

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

<? 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,D I would like to run an SQL Query to retrieve some of the columns with a WHERE clause like SQL. I understand that the =QUERY() function that works in the spreadsheet does not work inside the GAS. So my next attempt was to retrieve SOME of the rows by using a getBatch method .. and this is where I get ERRORs

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 :

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

<? var data = getData2(); ?>

with this code, I get the following error :

TypeError: Cannot read property "length" from undefined. (line 6, file "Code", project "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

I have seen this question but I am not able to understand the answer adequately


回答1:


You can use Google Visualization API Query Language to perform data manipulations with the query to the data source. The syntax of the query language is similar to SQL

code.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

<!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>



回答2:


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.

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;

}


来源:https://stackoverflow.com/questions/46924688/sql-like-query-features-in-google-app-script-to-pull-data-from-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!