เชื่อมต่อ Google Sheets กับ n8n เพื่อจัดการข้อมูลอัตโนมัติ
Prerequisites
Google Account Requirements
- ✅ Google Account ที่มี Google Drive
- ✅ Google Cloud Project (สำหรับ API)
- ✅ เปิดใช้ Google Sheets API
- ✅ Service Account หรือ OAuth 2.0
Required Information
- Spreadsheet ID (จาก URL)
- Sheet Name (ชื่อแผ่นงาน)
- API Credentials
Setup Google Sheets in n8n
1. Enable Google Sheets API
- ไปที่ Google Cloud Console
- สร้าง project ใหม่หรือใช้ project ที่มีอยู่
- ไปที่
APIs & Services→Library - ค้นหา
Google Sheets API - คลิก
Enable
2. Create Credentials
Option A: Service Account (Recommended)
- ไปที่
APIs & Services→Credentials - คลิก
Create Credentials→Service Account - กรอกข้อมูล:
Service account name: n8n-automation Service account description: n8n automation service - สร้าง key (JSON)
- ดาวน์โหลด JSON file
Option B: OAuth 2.0
- คลิก
Create Credentials→OAuth client ID - เลือก
Web application - กรอก redirect URI:
http://localhost:5678/oauth2/callback - ดาวน์โหลด credentials
3. Add Google Sheets Credential in n8n
- ไปที่
Settings→Credentials - คลิก
Add Credential - เลือก
Google Sheets - เลือก
Service AccountหรือOAuth2 - อัปโหลด JSON file หรือกรอกข้อมูล
- คลิก
Save
Basic Operations
1. Read Data from Sheets
สร้าง workflow พร้อม Google Sheets node:
Manual Trigger → Google Sheets (Read)
Google Sheets Node Settings:
- Operation:
Read - Document ID:
your-spreadsheet-id - Sheet Name:
Sheet1 - Range:
A1:Z1000
2. Append Data to Sheets
LINE Webhook → Function → Google Sheets (Append)
Function Node:
// แปลงข้อมูลจาก LINE
const message = $json.message;
const userId = $json.userId;
return [{
json: {
timestamp: new Date().toISOString(),
user_id: userId,
message: message,
processed: false
}
}];
Google Sheets Node Settings:
- Operation:
Append - Document ID:
your-spreadsheet-id - Sheet Name:
Messages - Columns:
[ { "column": "Timestamp", "value": "{{ $json.timestamp }}" }, { "column": "User ID", "value": "{{ $json.user_id }}" }, { "column": "Message", "value": "{{ $json.message }}" }, { "column": "Processed", "value": "{{ $json.processed }}" } ]
3. Update Data in Sheets
Schedule Trigger → Google Sheets (Read) → Function → Google Sheets (Update)
Function Node:
// อัปเดตสถานะ
const data = $input.all();
const updated = data.map(item => ({
...item.json,
processed: true,
updated_at: new Date().toISOString()
}));
return updated.map(item => ({ json: item }));
Advanced Examples
Customer Registration System
LINE Webhook → Function (Validate) → Google Sheets (Append) → LINE (Reply)
Function Node:
// ตรวจสอบข้อมูลการสมัคร
const message = $json.message;
const userId = $json.userId;
// แยกข้อมูล
const parts = message.split(',');
if (parts.length < 3) {
return [{
json: {
replyToken: $json.replyToken,
response: '❌ กรุณากรอกข้อมูลให้ครบ:\nชื่อ,เบอร์โทร,อีเมล\nตัวอย่าง: สมชาย,0812345678,somchai@email.com'
}
}];
}
const [name, phone, email] = parts.map(p => p.trim());
// ตรวจสอบรูปแบบ
if (!name || !phone.match(/^\d{10}$/) || !email.includes('@')) {
return [{
json: {
replyToken: $json.replyToken,
response: '❌ ข้อมูลไม่ถูกต้อง:\n- ชื่อ: ต้องไม่ว่าง\n- เบอร์: 10 หลัก\n- อีเมล: ต้องมี @'
}
}];
}
return [{
json: {
replyToken: $json.replyToken,
customerData: {
timestamp: new Date().toISOString(),
user_id: userId,
name: name,
phone: phone,
email: email,
status: 'pending'
},
response: `✅ ลงทะเบียนสำเร็จ!\nชื่อ: ${name}\nเบอร์: ${phone}\nอีเมล: ${email}\n\nเราจะติดต่อกลับโดยเร็วครับ`
}
}];
Order Tracking System
Schedule (Daily) → Google Sheets (Read Orders) → Function (Check Status) → Google Sheets (Update) → LINE (Notify)
Function Node:
// ตรวจสอบสถานะออเดอร์
const orders = $input.all();
const notifications = [];
for (const order of orders) {
const data = order.json;
// ตรวจสอบว่าผ่าน 3 วันแล้วยังไม่จัดส่ง
const orderDate = new Date(data.order_date);
const today = new Date();
const daysDiff = (today - orderDate) / (1000 * 60 * 60 * 24);
if (daysDiff > 3 && data.status === 'processing') {
notifications.push({
user_id: data.user_id,
message: `📦 อัปเดตสถานะออเดอร์ #${data.order_id}\nสถานะ: กำลังจัดเรียงสินค้า\nวันที่สั่ง: ${data.order_date}\n\nขออภัยในความล่าช้าครับ 🙏`
});
// อัปเดตสถานะ
data.status = 'delayed';
data.notification_sent = true;
}
}
return notifications.map(notif => ({ json: notif }));
Data Analysis Dashboard
Schedule (Hourly) → Google Sheets (Read) → Function (Analyze) → Google Sheets (Write Summary)
Function Node:
// วิเคราะห์ข้อมูล
const data = $input.all();
const analysis = {
total_messages: data.length,
unique_users: new Set(data.map(item => item.json.user_id)).size,
today_messages: data.filter(item => {
const date = new Date(item.json.timestamp);
const today = new Date();
return date.toDateString() === today.toDateString();
}).length,
top_keywords: {},
response_rate: 0
};
// นับคำที่พบบ่อย
const allMessages = data.map(item => item.json.message.toLowerCase()).join(' ');
const words = allMessages.match(/\b\w+\b/g) || [];
words.forEach(word => {
if (word.length > 2) {
analysis.top_keywords[word] = (analysis.top_keywords[word] || 0) + 1;
}
});
// เรียงคำที่พบบ่อยสุด 10 อันดับ
analysis.top_keywords = Object.entries(analysis.top_keywords)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.reduce((obj, [word, count]) => {
obj[word] = count;
return obj;
}, {});
return [{
json: {
timestamp: new Date().toISOString(),
...analysis
}
}];
Best Practices
Data Structure
- ✅ ใช้ header row อย่างสม่ำเสมอ
- ✅ กำหนด data types ให้ชัดเจน
- ✅ ใช้ timestamp สำหรับ tracking
Performance
- ✅ จำกัดการอ่านข้อมูล (ใช้ range)
- ✅ ใช้ batch operations
- ✅ หลีกเลี่ยงการ query ข้อมูลซ้ำ
Security
- ✅ ใช้ Service Account แทน personal account
- ✅ จำกัดการเข้าถึง (share settings)
- ✅ ไม่เก็บข้อมูล sensitive ใน sheets
Common Issues
Permission Denied
- ✅ ตรวจสอบ service account permissions
- ✅ แชร์ spreadsheet กับ service account
- ✅ ตรวจสอบ API enabled
Quota Exceeded
- ✅ Google Sheets API: 100 requests/100 seconds
- ✅ ใช้ batch operations
- ✅ จัดการ rate limiting
Data Format Issues
- ✅ ตรวจสอบ data types
- ✅ ใช้ ISO format สำหรับ dates
- ✅ หลีกเลี่ยง special characters
Next Steps
- Half-Stack Approach - พัฒนา custom features
- Client Examples - ดูตัวอย่างจริง
ต้องการความช่วยเหลือ? ติดต่อเราได้ที่ ShantiLink.com 💬