[轉貼]在Blogger顯示Google試算表的QUERY查詢結果

http://shanhua0131.blogspot.tw/

在Blogger顯示Google試算表的QUERY查詢結果


本文是Google Visualization API的運用,可以在部落格顯示Google試算表的QUERY查詢結果,點選欄位還有排序效果,程式碼是參考Google Code Playground 範例程式修改。

值得一提的是,所要連接的Google試算表如果是用新版製成的,QUERY的查詢指令可能會失效,我在陰錯陽差的狀況下將連接KEY換到舊表格一切就正常了。(PS:舊版的電子表格網址是如同「https://docs.google.com/spreadsheet/ccc?key=」這樣的),如果是新版試算表在試算表右下方會有如下的標誌

這個方法無法套用在Google的協作平台,因為該網頁空間好像不允許引用外部Script(都是自家的API了,怎會有這種限制)

如果想學習套用,請將程式碼以HTML編輯模式貼入文章內文中,並修改程式碼內文有標註//*修改地方(有2處)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>
Google Visualization API Sample
</title>
<script src="//www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google
.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
//var query = new google.visualization.Query(
// 'https://docs.google.com/spreadsheets/d/1SXPknVhdGumk-DLLWCijfMV8m11lWI0Fo-BbjF9WCHA/edit?usp=sharing');
//連接的spreadsheet(電子表格)如果是新版的,經測試Query的任何查詢指令似乎都會失效
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/ccc?key=0AkeHSKjTEDu_dDhqOXBXSDFuQm0xR284dkwwalZqWnc&usp=sharing');
//*修改地方1:new google.visualization.Query(Google試算表參照網址)要改成自己的網址

// Apply query language.
//相關QUERY語法請參照https://google-developers.appspot.com/chart/interactive/docs/querylanguage
//query.setQuery('SELECT A,B where D>1');//OK
//query.setQuery('SELECT * where upper(B) contains upper("ja")');//OK
query
.setQuery('SELECT * where upper(B) like upper("%jaC%")');//OK
//*修改地方2:query.setQuery(查詢語法)

// Send the query with a callback function.
query
.send(handleQueryResponse);
}

function handleQueryResponse(response) {
if (response.isError()) {
alert
('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}

// Create and draw the visualization.
var data = response.getDataTable();
visualization
= new google.visualization.Table(document.getElementById('table'));

<!-- visualization.draw(data, null); -->
visualization
.draw(data, {showRowNumber: true});
}

google
.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="border: 0 none; font-family: Arial;">
<div id="table">
</div>
</body>
</html>

套用後的效果如下(請在各標題欄位點一下會有排序效果,如果滑鼠移動到某一列顏色也會有變化)

TimeStamp UserID TimeBooked Type Month Year ID
1 2/9/2011 14:42:11 jackm 200 1 2 2011 2011-02
2 2/9/2011 14:42:11 jackm 500 2 2 2011 2011-02
3 2/9/2011 14:42:11 jac 600 3 3 X1 Y1
4 2/9/2011 14:42:11 JAc 800 5 5 X3 Y3