Chào các anh chị em trong diễn đàn,
Dạo này công việc của mình liên quan nhiều đến việc tổng hợp dữ liệu từ nhiều nguồn khác nhau, trong đó có cả Google Sheets. Mình muốn tự động hóa việc lấy dữ liệu từ Google Sheets về Excel để xử lý tiếp, thay vì phải copy-paste thủ công mỗi ngày. Sau một thời gian tìm hiểu, mình đã tìm ra cách làm với Python và Google Sheets API. Nay chia sẻ lại cho anh em nào cần nhé.
Tại sao lại dùng Python và Google Sheets API?
- Tự động hóa hoàn toàn, tiết kiệm thời gian và giảm thiểu sai sót.
- Python có thư viện mạnh mẽ hỗ trợ làm việc với Excel (
openpyxl,pandas) và Google Sheets API. - Dễ dàng tùy chỉnh logic lấy dữ liệu, lọc, và xử lý trước khi đưa vào Excel.
Các bước cơ bản:
- Cài đặt thư viện cần thiết:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib pandas openpyxl - Thiết lập Google Cloud Project và Google Sheets API: Bạn cần tạo một project trên Google Cloud Console, bật Google Sheets API và tạo tài khoản dịch vụ (Service Account) để xác thực. Tải file JSON khóa của tài khoản dịch vụ về máy.
- Viết mã Python: Sử dụng thư viện
google-api-python-clientđể kết nối và lấy dữ liệu từ Google Sheet. Sau đó, dùngpandasđể xử lý dữ liệu và lưu vào file Excel bằngopenpyxl.
Ví dụ đoạn mã lấy dữ liệu (minh họa):
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SERVICE_ACCOUNT_FILE = 'path/to/your/service_account.json'
SPREADSHEET_ID = 'YOUR_SPREADSHEET_ID'
RANGE_NAME = 'Sheet1!A1:Z100'
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
# Xử lý dữ liệu 'values' ở đây (ví dụ: chuyển thành DataFrame pandas)
print(f'Loaded {len(values)} rows.')
Sau khi lấy được dữ liệu, bạn có thể dùng pandas để tạo DataFrame và lưu vào Excel:
import pandas as pd
# Giả sử 'values' đã được xử lý thành danh sách các danh sách hoặc cấu trúc phù hợp
df = pd.DataFrame(values[1:], columns=values[0]) # Nếu dòng đầu là header
df.to_excel('output.xlsx', index=False)
Hy vọng chia sẻ này hữu ích cho mọi người. Nếu có ai đã từng làm hoặc có cách nào hay hơn, cùng thảo luận nhé!