想要在 Google Sheet 中自動獲取台灣的天氣資訊?你可以使用 Google Apps Script,這是 Google 提供的一個程式化工具,能夠在 Google Sheet 中執行自訂的腳本,讓你自動從中央氣象局獲取天氣資訊並將其寫入你指定的 Google Sheet。
以下是一個簡單的步驟,教你如何使用 Google Apps Script 實現這個目標:
準備工作
- 取得中央氣象局 API 金鑰: 首先,前往中央氣象局的網站,註冊並獲取 API 金鑰,這將允許你從他們的 API 獲取天氣資訊。
- 開啟 Google Sheet: 打開你想要將天氣資訊寫入的 Google Sheet。
建立 Google Apps Script
- 在 Google Sheet 中,點選上方的「擴充功能」>「Apps Script」,這會開啟 Google Apps Script 編輯器。
- 在編輯器中,將下面的程式碼貼上:
function fetchAndWriteWeather() {
var apiKey = '你的中央氣象局API金鑰';
var location = '臺北市'; // 你想要查詢的地區
var apiUrl = 'https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?locationName=' + location + '&Authorization=' + apiKey;
var response = UrlFetchApp.fetch(apiUrl);
var weatherData = response.getContentText();
var json = JSON.parse(weatherData);
var weatherDescription = json.records.location[0].weatherElement[0].time[0].parameter.parameterName;
var temperature = json.records.location[0].weatherElement[1].time[0].parameter.parameterName;
var spreadsheetId = '你的Google Sheet的ID';
var sheetName = '工作表名稱'; // 請替換為你的工作表名稱
var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
sheet.getRange('A1').setValue(weatherDescription);
sheet.getRange('B1').setValue(temperature);
}
設定觸發器
- 在編輯器中,點選左上角的時鐘圖示,新增觸發器。
- 選擇時間驅動觸發器,設定腳本定期執行的時間,例如每小時、每天等。
儲存並執行
- 點選左上角的磁碟圖示,儲存你的腳本。
- 手動執行腳本,確保它能夠正常運作。
檢查結果
- 回到你的 Google Sheet,應該能夠看到在你指定的位置(例如 A1 和 B1 儲存格)中出現天氣描述和溫度資訊。