这是一个稍微旧的线程,但是关于如何做到这一点的例子很少,我认为再有一个也不会受到伤害。您可以将 SQL 语句传递到下面的 querySpreadsheet() 函数中,例如:
var querySQL = "SELECT A, B, C, D WHERE C = 'Project X' AND (D = 'Task 1' OR D = 'Task 2')";
然后,您可以将函数返回的数据数组拖放到目标工作表中,如下所示:
var aryValues = querySpreadsheet(querySQL);
SpreadsheetApp.getActiveSpreadsheet().getRangeByName('OUTPUT_TOPLEFT_CELL').offset(0, 0, aryValues.length, 4).setValues(aryValues);
这些功能几乎可以使用,只需在指示的地方替换您的信息即可。感谢 Mogsdad 提供此脚本的原始版本:
在发送到 Google Apps 脚本仪表板之前使用 QUERY URL 对数据进行分组
function querySpreadsheet(querySQL){
try {
//you can find both these items in the url of your spreadsheet
var ssKey = 'DOCUMENT KEY OF THE DATA SOURCE SPREADSHEET INSIDE THESE QUOTES - long code ends with "&" starts with "key="';
var gId = 'INDEX OF THE SHEET CONTAINING THE DATA - starts with "gid="';
var query = encodeURIComponent(querySQL);
var url = 'http://spreadsheets.google.com/tq?key=%KEY%&gid=%GID%&tq=%QUERY%'
.replace('%KEY%',ssKey)
.replace('%QUERY%',query)
.replace('%GID%',gId);
var response = UrlFetchApp.fetch(url);
var content = response.getContentText();
var jsonContent = getJSON(content);
var numCols = jsonContent.table.cols.length;
var numRows = jsonContent.table.rows.length;
// Decode objectContent into a two-dimensional array.
var mydata = [];
// Then data rows
for (var row = 0; row < numRows; row++) {
mydata[row] = [];
for (var col = 0; col < numCols; col++ ) {
mydata[row].push(jsonContent.table.rows[row].c[col].v);
}
}
return mydata;
} catch(error) {
Logger.log('querySpreadsheet: ERROR - ', error);
};
};
//the content text format is not uniform; try 2 methods to return a JSON object
function getJSON(contentText) {
try {
var regex = /.*google.visualization.Query.setResponse\((.*)\)/g
var ret = eval('('+ regex.exec(contentText)[1] +')');
return ret;
} catch(error) {
var ret = regex.exec(contentText)[1];
var ret = Utilities.jsonParse(ret);
return ret;
};
};