本文件示範如何從 Quarto 報告中將資料輸出至 Google Sheets。此功能使用 Google Workload Identity Federation (WIF) 進行驗證,無需手動管理服務帳戶金鑰。
運作方式:
在 Pull Request 時,資料會輸出到預覽用的 Shared Drive 資料夾
合併到 main 分支後,資料會輸出到正式的 BI Shared Drive
範例資料
這是一個簡單的銷售摘要資料,我們將把它輸出到 Google Sheets:
程式碼
# Create sample sales datasales_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 claritysheet_name =f"Lighthouse_Demo_{google_sheets_env}_{date.today().strftime('%Y%m%d')}"# Use the helper function to create and move the sheetsheet_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