Google Sheets 整合示範

作者

BI Team

發佈於

2025年12月5日

概述

本文件示範如何從 Quarto 報告中將資料輸出至 Google Sheets。此功能使用 Google Workload Identity Federation (WIF) 進行驗證,無需手動管理服務帳戶金鑰。

運作方式:

  • 在 Pull Request 時,資料會輸出到預覽用的 Shared Drive 資料夾
  • 合併到 main 分支後,資料會輸出到正式的 BI Shared Drive

範例資料

這是一個簡單的銷售摘要資料,我們將把它輸出到 Google Sheets:

程式碼
# Create sample sales data
sales_data = pl.DataFrame({
    "store": ["屏東", "潮州", "恆春", "東港"],
    "daily_avg_sales": [45000, 38000, 25000, 32000],
    "daily_avg_tickets": [120, 95, 65, 85],
}).with_columns(
    (pl.col("daily_avg_sales") / pl.col("daily_avg_tickets")).round(0).alias("avg_ticket_value"),
    pl.lit(date.today().isoformat()).alias("report_date"),
    pl.lit(google_sheets_env).alias("environment"),
)

# Display the data with Chinese column names using great_tables
(
    GT(sales_data)
    .cols_label(
        store="門市",
        daily_avg_sales="日均銷售額",
        daily_avg_tickets="日均票數",
        avg_ticket_value="客單價",
        report_date="報告日期",
        environment="環境",
    )
    .fmt_number(columns=["daily_avg_sales", "daily_avg_tickets"], decimals=0, use_seps=True)
    .fmt_number(columns="avg_ticket_value", decimals=0, use_seps=True)
)
門市 日均銷售額 日均票數 客單價 報告日期 環境
屏東 45,000 120 375 2025-12-05 production
潮州 38,000 95 400 2025-12-05 production
恆春 25,000 65 385 2025-12-05 production
東港 32,000 85 376 2025-12-05 production

輸出至 Google Sheets

程式碼
# Sheet name includes environment and date for clarity
sheet_name = f"Lighthouse_Demo_{google_sheets_env}_{date.today().strftime('%Y%m%d')}"

# Use the helper function to create and move the sheet
sheet_url = google_write_sheet(
    data=sales_data,
    sheet_name=sheet_name,
    sheet_tab="sales_summary",
)

if sheet_url:
    print(f"\n**Sheet URL:** {sheet_url}")
Created sheet: https://docs.google.com/spreadsheets/d/1hAUH3Bo35A_9fxJsExOSyZAX26dEeTaGi6-LyoDSaVg

**Sheet URL:** https://docs.google.com/spreadsheets/d/1hAUH3Bo35A_9fxJsExOSyZAX26dEeTaGi6-LyoDSaVg

技術說明

Workload Identity Federation

本專案使用 GCP Workload Identity Federation (WIF) 來進行驗證。這種方式的優點:

  1. 無需管理金鑰:不需要儲存或輪換服務帳戶 JSON 金鑰
  2. 安全性更高:驗證基於 GitHub OIDC token,而非靜態憑證
  3. 自動化友善:在 CI/CD 環境中自動運作

驗證流程

GitHub Actions
    ↓ (OIDC token)
GCP Workload Identity Federation
    ↓ (exchange)
GCP Service Account (bi-publisher)
    ↓ (gcloud auth print-access-token)
Access Token
    ↓
Google Sheets API

環境變數

變數 用途
GOOGLE_ACCESS_TOKEN GCP 存取權杖 (由 gcloud 取得)
GOOGLE_SHEETS_FOLDER_ID 目標 Shared Drive 資料夾 ID
GOOGLE_SHEETS_ENV 環境標識 (preview/production)

下一步

  • 將此範例擴展到實際的營運報表
  • 設定自動排程更新(例如:每日營收報表)
  • 整合更多資料來源(資料庫查詢、API 等)