Google Sheets Integration

Connect Google Sheets with n8n for data management and automation

เชื่อมต่อ 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

  1. ไปที่ Google Cloud Console
  2. สร้าง project ใหม่หรือใช้ project ที่มีอยู่
  3. ไปที่ APIs & ServicesLibrary
  4. ค้นหา Google Sheets API
  5. คลิก Enable

2. Create Credentials

  1. ไปที่ APIs & ServicesCredentials
  2. คลิก Create CredentialsService Account
  3. กรอกข้อมูล:
    Service account name: n8n-automation
    Service account description: n8n automation service
    
  4. สร้าง key (JSON)
  5. ดาวน์โหลด JSON file

Option B: OAuth 2.0

  1. คลิก Create CredentialsOAuth client ID
  2. เลือก Web application
  3. กรอก redirect URI: http://localhost:5678/oauth2/callback
  4. ดาวน์โหลด credentials

3. Add Google Sheets Credential in n8n

  1. ไปที่ SettingsCredentials
  2. คลิก Add Credential
  3. เลือก Google Sheets
  4. เลือก Service Account หรือ OAuth2
  5. อัปโหลด JSON file หรือกรอกข้อมูล
  6. คลิก 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


ต้องการความช่วยเหลือ? ติดต่อเราได้ที่ ShantiLink.com 💬