Google visualization API (gviz) query and fetching data from a spreadsheet

风格不统一 提交于 2021-01-27 21:29:00

问题


I am using the Google Visualization API to query a spreadsheet. If I paste the URL in the browser:

https://docs.google.com/spreadsheets/d/14dIMLkVwHRo-bkvdIhaDwC-rGBHLefftlC6CCCs5YrWSc/gviz/tq?sheet=customers&tq=select+*+Where+A='27938'

A is the customer ID column. I get this JSON looking text back: google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"7671558882","table":{"cols":[{"id":"A","label":"ID","type":"string"},{"id":"B","label":"FirstName",.....

1) How can I do the same within a google script function (not from the client side javascript function)?

I tried using the URLFetchApp.fetc():

var url = 'https://docs.google.com/spreadsheets/d/14dIMLkVwHRo-bkvdIhaDwC-rGBHLefftlC6CCCs5YrWSc/gviz/tq?sheet=customers&tq=select+*+Where+A=27938'
var result = URLFetchApp.fetch(url);
var out = JSON.parse(result.getContentText());
Logger.log(out);

The logger shows a long list of CSS style definitions and HTML tags. If I can get the JSON response and parse it, I was planning to do some business logic within the function return a value to the client.


回答1:


I found problems with google sheets/gvis query too - for unnown reason Google Sheets returns not pure JSON but add some s*** to it, so before use JSON.parse() we need to cut it of (or crop the usefull part of the response):

var httpresponse = UrlFetchApp.fetch(urlrequest, options).getContentText();

var from = httpresponse.indexOf("{");
var to   = httpresponse.lastIndexOf("}")+1;

var jsonText = httpresponse.slice(from, to);

var parsedText = JSON.parse(jsonText);



回答2:


I think you would need to call the function openByID in apss script (documentation) then call the method getRange(), then you will receive a two dimension array with the information of the sheet.

with this then you can create the JSON to use the chart services (docs)

There are probably some libraries that already. Check this website, you may find the one you need. Hope this helps.




回答3:


The reason you're getting "CSS style definitions and HTML tags" is the error in the request.

Here's the error text:

This spreadsheet is not publicly viewable and requires an OAuth credential. For more information, see https://support.google.com/docs/?p=gviz_tq_auth

Share the file to solve it:

Here's the sample code I used to get the query result as 2D array:

Usage

function test_getSheetsQueryResult()
{
  var fileId = '1WO3PEycHGtfG-yd4V-B6EfKkVYMC73EqDBPqgAqcz3k';
  var sheetName = 'Data';
  var rangeA1 = 'A1:H11';
  var sqlText = "select A, C, D, F, 'google' where E > 0";

  var res = getSheetsQueryResult_(fileId, sheetName, rangeA1, sqlText);
  Logger.log(res);

}

Code:

/*   
  Types:

    Get             Return
    number    =>    number
    string    =>    string
    date      =>    string
    datetime  =>    string
    boolean   =>    boolean

  Note: 

    The function returns strings for dates because of 2 resons:
      1. The string is automatically converted into a date when pasted into the sheet
      2. There are multiple issues with dates (like different time zones) that could modify returned values
*/
function getSheetsQueryResult_(fileId, sheetName, rangeA1, sqlText)
{

  var file = SpreadsheetApp.openById(fileId);
  var sheetId = file.getSheetByName(sheetName).getSheetId();

  var request = 'https://docs.google.com/spreadsheets/d/' + fileId + '/gviz/tq?gid=' + sheetId + '&range=' + rangeA1 + '&tq=' + encodeURIComponent(sqlText);
  var result = UrlFetchApp.fetch(request).getContentText();     
  // get json object
  var from = result.indexOf("{");
  var to   = result.lastIndexOf("}")+1;  
  var jsonText = result.slice(from, to);  
  var parsedText = JSON.parse(jsonText);      

  // get types
  var types = [];
  var addType_ = function(col) { types.push(col.type); }
  var cols = parsedText.table.cols;
  cols.forEach(addType_);    

  // loop rows
  var rows = parsedText.table.rows;  
  var result = [];  
  var rowQuery = [];
  var eltQuery = {};
  var row = [];
  var nRows = rows[0].c.length;
  var type = '';
  for (var i = 0, l = rows.length; i < l; i++)
  {
    rowQuery = rows[i].c;
    row = [];
    // loop values   
    for (var k = 0; k < nRows; k++)
    {
      eltQuery = rowQuery[k];
      type = types[k];
      if (type === 'number') { row.push(parseInt(eltQuery.v)); }
      if (type === 'boolean' || type === 'string') { row.push(eltQuery.v); }
      else { row.push(eltQuery.f); }      
    }    
    result.push(row);
  }

  return result;

}


来源:https://stackoverflow.com/questions/29202686/google-visualization-api-gviz-query-and-fetching-data-from-a-spreadsheet

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