Wix 網頁製作 - Apps Script 程式碼
- 作 振
- 2025年6月13日
- 讀畢需時 3 分鐘
// ====== 設定你的 Google Sheet 資訊 ======
const SPREADSHEET_NAME = 'Wix_誠菓手作_預約行程'; // 你的 Google Sheet 名稱
const SHEET_NAME = '日期與數量'; // 你的工作表名稱 (例如:Sheet1, 資料)
/**
* 處理 GET 請求
* 當 Wix Velo 發送 GET 請求到這個 Web App 時,會觸發這個函式。
* 用於讀取 Google Sheet 的資料。
* * 測試方法:直接在瀏覽器中訪問部署後的 Web App URL,或使用 Wix Velo 發送 GET 請求。
*/
function doGet(e) {
try {
const ss = SpreadsheetApp.getActiveSpreadsheet(); // 獲取當前綁定的試算表
const sheet = ss.getSheetByName(SHEET_NAME);
if (!sheet) {
return createJsonResponse({ error: '工作表未找到:' + SHEET_NAME }, 404);
}
const range = sheet.getDataRange(); // 獲取所有資料範圍
const values = range.getValues(); // 獲取所有儲存格的值
// 如果想只獲取除了標題行的數據
const headers = values[0]; // 第一行是標題
const dataRows = values.slice(1); // 從第二行開始是數據
// 將數據轉換為物件陣列,方便 Wix Velo 處理
const formattedData = dataRows.map(row => {
const obj = {};
headers.forEach((header, index) => {
const value = row[index]; // 這裡的 value 是從 Google Sheet 讀取到的原始值,如果是日期欄位,它會是一個 Date 物件
// >>> 這裡就是你需要使用的程式碼:將日期物件 'value' 格式化為字串 <<<
if (header === '預約日期' && value instanceof Date) {
// --- 關鍵修改:直接從年、月、日組合成字串 ---
const year = value.getFullYear();
// 月份是從 0 開始 (0-11),所以需要加 1
const month = value.getMonth() + 1;
const day = value.getDate();
// 為了確保月和日是兩位數 (例如 01, 02),進行填充
const formattedMonth = month < 10 ? '0' + month : month;
const formattedDay = day < 10 ? '0' + day : day;
// 拼接成 "yyyy/MM/dd" 格式的字串
obj[header] = `${year}/${formattedMonth}/${formattedDay}`;
// --- 結束關鍵修改 ---
} else {
// 對於其他非日期欄位,保持原樣
obj[header] = value;
}
});
return obj;
});
console.log(formattedData)
return createJsonResponse({ success: true, data: formattedData }, 200);
} catch (error) {
console.error("GET 請求錯誤:", error.toString());
return createJsonResponse({ error: '處理 GET 請求時發生錯誤:' + error.toString() }, 500);
}
}
/**
* 處理 POST 請求
* 當 Wix Velo 發送 POST 請求到這個 Web App 時,會觸發這個函式。
* 用於將資料寫入 Google Sheet。
* * 預期 POST 請求的 body 是一個 JSON 物件,例如:
* {
* "日期": "2025/06/12",
* "數量": 150,
* "備註": "新增一筆資料"
* }
*/
function doPost(e) {
try {
// 解析 POST 請求的 JSON body
const requestBody = JSON.parse(e.postData.contents);
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(SHEET_NAME);
if (!sheet) {
return createJsonResponse({ error: '工作表未找到:' + SHEET_NAME }, 404);
}
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; // 獲取標題行
// 根據標題順序構建要寫入的行數據
const newRow = [];
headers.forEach(header => {
newRow.push(requestBody[header] || ''); // 如果請求中沒有該欄位,則為空字串
});
sheet.appendRow(newRow); // 將新行添加到工作表末尾
return createJsonResponse({ success: true, message: '資料已成功寫入 Google Sheet' }, 200);
} catch (error) {
console.error("POST 請求錯誤:", error.toString());
return createJsonResponse({ error: '處理 POST 請求時發生錯誤:' + error.toString() }, 500);
}
}
/**
* 輔助函式:創建 JSON 回應
*/
function createJsonResponse(data, statusCode) {
return ContentService.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON);
}
留言