# 實戰 Google App Script
[toc]
## 先動手試試看 GAS
> [GAS網站](https://script.google.com/home)
>
原本:
```javascript=
function doGet() {
return "Hi, GAS";
}
```
更改後的 - 1:
```javascript=
function doGet() {
return ContentService.createTextOutput("<h1>123</h1>");
}
```
更改後的 - 2:
```javascript=
function doGet() {
return HtmlService.createHtmlOutput("<h1>123</h1>");
}
```
## 實作一:表單通知
### > 取得Linr Notify 權杖
> 快速連結:[Line Notify](https://notify-bot.line.me/zh_TW/)
- Step 1
![](https://i.imgur.com/kHCMeNL.png)
- Step 2
![](https://i.imgur.com/xnmY7S7.png)
- Step 3
![](https://i.imgur.com/GPziKWi.png)
### > 建立Google表單 & 連結試算表
- 隨意設計一張表單,並連結試算表
![](https://i.imgur.com/JNjk2ER.png)
### > 連結Google App Script
- 進入試算表,點選 [擴充功能] > [App Script]
![](https://i.imgur.com/YScMiBr.png)
### > 與Line Notify建立連結
> 參考資料:[LINE Notify API Document](https://notify-bot.line.me/doc/en/)
- 建立函式,讓GAS可以傳送資料到Line Notify
```javascript=
function sendLineNotify(message, token) {
var options =
{
"method": "post",
"payload": { "message": message },
"headers": { "Authorization": "Bearer " + token }
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
```
### > 取得試算表資料
```javascript=
function getFormData(e) {
// 貼入Token
var token = "放上你的 Line Notify token";
var spreadSheet = SpreadsheetApp.getActive();
var sheet = spreadSheet.getActiveSheet();
var lastColumn = sheet.getLastColumn();
var sheetData = sheet.getSheetValues(1, 1, 1, lastColumn);
var message = "\n";
//組合訊息
/* To-Do */
sendLineNotify(message, token);
}
```
:::spoiler Full Code
```javascript=
function getFormData(e) {
// 貼入Token
var token = "放上你的 Line Notify token";
var spreadSheet = SpreadsheetApp.getActive();
var sheet = spreadSheet.getActiveSheet();
var lastColumn = sheet.getLastColumn();
var sheetData = sheet.getSheetValues(1, 1, 1, lastColumn);
var message = "\n";
//組合訊息
for (var i = 0; i < lastColumn; i++) {
if (e.values[i] !== "") {
if (sheetData[0][i] !== "") {
message += sheetData[0][i] + ":" + e.values[i] + "\n";
}
}
}
sendLineNotify(message, token);
}
```
:::
![](https://i.imgur.com/p4LMe8T.png =650x)
### > 設定觸發條件
![](https://i.imgur.com/m3lKSW4.png =600x)
![](https://i.imgur.com/lqWwONv.png =600x)
## 實作2:資料查詢
### > 取得資料集
> 112年台科大宿舍抽籤名單:[File](https://s.merlinkuo.tw/0502data)
- [檔案] > [建立副本]
![](https://i.imgur.com/G20BmTs.png)
### > 連結Google App Script
- 進入試算表,點選 [擴充功能] > [App Script]
![](https://i.imgur.com/YScMiBr.png)
### > 撰寫GAS Code
> 參考資料:[YouTube](https://youtu.be/MQV3AlAOtCU)
```javascript=
function doGet(e) {
// 取得uid
/* To-Do */
// 取得資料表資訊
var Sheet = SpreadsheetApp.getActiveSheet();
var LastRow = Sheet.getLastRow();
//var LastColumn = Sheet.getLastColumn();
var data = [];
// 取得全部資料
var listAll = Sheet.getSheetValues(1, 1, LastRow, 4);
// 存標題
data.push({data: listAll[0]})
// 找尋資料是否有存在
/* To-Do */
//顯示資料
Logger.log(data);
// 回傳json資料
/* To-Do */
}
```
:::spoiler Full Code
```javascript=
function doGet(e) {
// 取得uid
var params = e.parameter;
var uid = params.uid;
// 取得資料表資訊
var Sheet = SpreadsheetApp.getActiveSheet();
var LastRow = Sheet.getLastRow();
var LastColumn = Sheet.getLastColumn();
var data = [];
// 取得全部資料
var listAll = Sheet.getSheetValues(1, 1, LastRow, 4);
//存標題
data.push({data: listAll[0]})
// 找尋資料是否有存在
for(var i = 1;i < listAll.length; i++){
if(listAll[i][1]==uid){
data.push({data: listAll[i]})
}
}
//顯示資料
Logger.log(data);
// 回傳json資料
return ContentService.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON);
}
```
:::
### > 發佈 & 測試
- 記得選取【所有人】
![](https://i.imgur.com/qOb31Z2.png)
- 把取得的網址輸入瀏覽器,並在最後加上?uid=B11015024
> 範例
```
https://script.google.com/macros/s/{YOUR_GAS_ID}/exec?uid=B11015024
```
- 你應該會看到
```json!
[{"data":["正/備取號","學號 (Student ID NO.)","姓名 (Name)",""]},{"data":["備取518","B11015024","郭○晨",""]}]
```
~~對!我就是沒抽到宿舍QQ~~
### > 撰寫HTML前端網頁
```htmlmixed=
<html>
<style>
body {
font-family: 微軟正黑體;
font-size: 20px;
padding: 2%;
}
</style>
<head>
<meta charset="UTF-8" />
</head>
<body>
輸入學號:<input type="text" id="uid" />
<input type="button" name="inq" value="查詢" onclick="showHint(uid.value);"></br>
<span id="order_status"></span>
<script type="text/javascript">
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 解析回傳值並顯示
/* To-Do */
}
}
// 傳送請求
/* To-Do */
var url = "{Put your url here}";
}
</script>
</body>
</html>
```
:::spoiler Full Code
```javascript=
<html>
<style>
body {
font-family: 微軟正黑體;
font-size: 20px;
padding: 2%;
}
</style>
<head>
<meta charset="UTF-8" />
</head>
<body>
輸入學號:<input type="text" id="uid" />
<input type="button" name="inq" value="查詢" onclick="showHint(uid.value);"></br>
<span id="order_status"></span>
<script type="text/javascript">
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 解析回傳值並顯示
var result = xmlhttp.responseText;
var obj = JSON.parse(result);//解析json字串為json物件形式
if (obj.length == 1) //只有一筆代表查不到資料
var html = '</br>查無資料,請確認學號是否正確!';
if (obj.length != 1) {
var html = '</br>姓名:' + obj[1].data[2] + '</br>中籤序號:' + obj[1].data[0];
}
document.getElementById("order_status").innerHTML = html;
}
}
// 傳送請求
var url = "{Put your url here}";
xmlhttp.open("get", url + "?uid=" + encodeURIComponent(str), true);
xmlhttp.send();
}
</script>
</body>
</html>
```
:::