Kỹ thuật

Tích hợp Google Sheets với các ứng dụng khác qua API

Hoàng Mạnh TuânHoàng Mạnh Tuân
28 tháng 12, 2025
Cập nhật: 7 tháng 8, 2026
18 phút đọc
Ảnh minh họa bài viết: Tích hợp Google Sheets với các ứng dụng khác qua API

Google Sheets không chỉ là bảng tính - nó có thể là trung tâm dữ liệu cho toàn bộ hệ thống của bạn!

Tổng quan các phương pháp tích hợp

Phương pháp Độ khó Use Case
IMPORTDATA Lấy CSV từ URL
IMPORTHTML Scrape web tables
IMPORTRANGE Liên kết Sheets
Apps Script + UrlFetch ⭐⭐⭐ API calls
Webhooks ⭐⭐⭐ Real-time events
Google Sheets API ⭐⭐⭐⭐ External apps

1. IMPORTDATA - Lấy dữ liệu CSV

Cú pháp:

=IMPORTDATA("https://example.com/data.csv")

Ví dụ thực tế:

// Lấy tỷ giá từ API
=IMPORTDATA("https://api.exchangerate-api.com/v4/latest/USD")

2. IMPORTHTML - Scrape web

Cú pháp:

=IMPORTHTML("URL", "table", index)
=IMPORTHTML("URL", "list", index)

Ví dụ:

// Lấy bảng từ Wikipedia
=IMPORTHTML("https://vi.wikipedia.org/wiki/...", "table", 1)

3. Apps Script - Gọi API

GET request:

function fetchData() {
  const url = 'https://api.example.com/data';
  const options = {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response.getContentText());

  // Ghi vào sheet
  const sheet = SpreadsheetApp.getActiveSheet();
  data.forEach((item, index) => {
    sheet.getRange(index + 2, 1, 1, Object.keys(item).length)
      .setValues([Object.values(item)]);
  });
}

POST request:

function postData() {
  const url = 'https://api.example.com/create';
  const payload = {
    name: 'Test Product',
    price: 100000
  };

  const options = {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

4. Tích hợp với Slack

Gửi thông báo đến Slack:

function sendToSlack(message) {
  const webhookUrl = 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL';

  const payload = {
    text: message,
    username: 'Google Sheets Bot',
    icon_emoji: ':spreadsheet:'
  };

  UrlFetchApp.fetch(webhookUrl, {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  });
}

// Trigger khi có thay đổi
function onEdit(e) {
  if (e.range.getSheet().getName() === 'Orders') {
    sendToSlack(`📦 Đơn hàng mới: ${e.range.getValue()}`);
  }
}

5. Tích hợp với Telegram

Gửi tin nhắn Telegram:

function sendTelegram(message) {
  const botToken = 'YOUR_BOT_TOKEN';
  const chatId = 'YOUR_CHAT_ID';

  const url = `https://api.telegram.org/bot${botToken}/sendMessage`;

  UrlFetchApp.fetch(url, {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify({
      chat_id: chatId,
      text: message,
      parse_mode: 'HTML'
    })
  });
}

// <a href="/blog/bao-cao-doanh-thu-phan-tich-ban-hang" title="Báo Cáo Doanh Thu & Phân Tích Bán Hàng">Báo cáo doanh thu</a> hàng ngày
function dailyReport() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Dashboard');
  const revenue = sheet.getRange('B2').getValue();
  const orders = sheet.getRange('C2').getValue();

  const message = `
📊 <b>Báo cáo hôm nay</b>

💰 Doanh thu: ${revenue.toLocaleString('vi-VN')}đ
📦 Đơn hàng: ${orders}
  `;

  sendTelegram(message);
}

6. Web App - Nhận Webhook

Tạo endpoint nhận dữ liệu:

function doPost(e) {
  try {
    const data = JSON.parse(e.postData.contents);

    const sheet = SpreadsheetApp.getActiveSpreadsheet()
      .getSheetByName('Webhooks');

    sheet.appendRow([
      new Date(),
      data.event,
      JSON.stringify(data.payload)
    ]);

    return ContentService
      .createTextOutput(JSON.stringify({ success: true }))
      .setMimeType(ContentService.MimeType.JSON);

  } catch (error) {
    return ContentService
      .createTextOutput(JSON.stringify({ error: error.message }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

function doGet(e) {
  return ContentService
    .createTextOutput('Webhook endpoint is ready!')
    .setMimeType(ContentService.MimeType.TEXT);
}

Deploy as Web App:

  1. Deploy → New deployment
  2. Type: Web app
  3. Execute as: Me
  4. Who has access: Anyone
  5. Copy URL và dùng làm webhook endpoint

7. Đồng bộ với CRM (Ví dụ: HubSpot)

function syncToHubSpot() {
  const apiKey = 'YOUR_HUBSPOT_API_KEY';
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getDataRange().getValues();

  // Bỏ qua header row
  for (let i = 1; i < data.length; i++) {
    const [email, firstName, lastName, phone] = data[i];

    const url = 'https://api.hubapi.com/crm/v3/objects/contacts';

    const payload = {
      properties: {
        email: email,
        firstname: firstName,
        lastname: lastName,
        phone: phone
      }
    };

    try {
      UrlFetchApp.fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        payload: JSON.stringify(payload)
      });

      // Đánh dấu đã sync
      sheet.getRange(i + 1, 5).setValue('Synced');

    } catch (error) {
      sheet.getRange(i + 1, 5).setValue('Error: ' + error.message);
    }

    // Tránh rate limit
    Utilities.sleep(500);
  }
}

8. Tích hợp với Google Forms

Auto-process form submissions:

function onFormSubmit(e) {
  const responses = e.namedValues;

  // Gửi email xác nhận
  const email = responses['Email'][0];
  const name = responses['Họ tên'][0];

  GmailApp.sendEmail(
    email,
    'Cảm ơn bạn đã đăng ký!',
    `Xin chào ${name},\n\nChúng tôi đã nhận được thông tin của bạn.`
  );

  // Thông báo Slack
  sendToSlack(`🎉 Đăng ký mới từ ${name} (${email})`);

  // Cập nhật CRM
  // ...
}

9. Zapier / Make Integration

Nếu không muốn code, dùng Zapier hoặc Make:

  1. Trigger: Google Sheets - New Row
  2. Action: Slack - Send Message
  3. Action: HubSpot - Create Contact

Best Practices

1. Error Handling:

try {
  // API call
} catch (error) {
  Logger.log('Error: ' + error.message);
  // Retry logic hoặc alert
}

2. Rate Limiting:

Utilities.sleep(1000); // 1 giây giữa các request

3. Secure API Keys:

const apiKey = PropertiesService.getScriptProperties().getProperty('API_KEY');

4. Logging:

console.log('Request sent at', new Date());
console.log('Response:', response.getContentText());

Kết luận

Google Sheets có thể tích hợp với hầu hết các ứng dụng thông qua API. Bắt đầu với những tích hợp đơn giản như Slack, Telegram trước khi tiến đến các hệ thống phức tạp hơn như CRM, ERP.

Tip: Các phần mềm trên SheetStore đã được tích hợp sẵn nhiều tính năng API, giúp bạn tiết kiệm thời gian phát triển!

Chia sẻ bài viết:

Hoàng Mạnh Tuân

Hoàng Mạnh Tuân

Bạn thấy bài viết hữu ích?

Đăng ký nhận thông báo khi có bài viết mới.

Nhận thông báo khi có bài viết mới. Không spam, hứa luôn! 😊

Bình luận (0)

Vui lòng đăng nhập để tham gia thảo luận