You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab多DataFrame导出多Sheet Excel本地下载及获取用户名

问题解决方案

一、实现Excel文件直接下载到本地

你的代码默认将文件保存到Colab虚拟机或挂载的Drive中,要让用户点击按钮后直接下载到本地,需结合Colab的files模块触发浏览器下载。示例代码如下:

import pandas as pd
from google.colab import files

# 假设df1、df2、df3是已准备好的DataFrame
file_name = "dashboard_tables.xlsx"

# 将多表写入Excel文件(先存到Colab虚拟机临时目录)
with pd.ExcelWriter(file_name) as writer:
    df1.to_excel(writer, sheet_name='df1')
    df2.to_excel(writer, sheet_name='df2')
    df3.to_excel(writer, sheet_name='df3')

# 触发浏览器下载,文件会直接保存到用户本地下载目录
files.download(file_name)

如果是在仪表盘(如Streamlit、ipywidgets)中使用,只需将上述下载逻辑绑定到按钮的点击回调函数即可。

二、获取Google Colab当前用户的用户名

通过调用Google People API可获取当前登录用户的邮箱,进而提取用户名。代码如下:

from google.colab import auth
import google.auth
from googleapiclient.discovery import build

# 完成身份验证(首次运行需授权)
auth.authenticate_user()
credentials, _ = google.auth.default()

# 调用API获取用户邮箱信息
service = build('people', 'v1', credentials=credentials)
profile = service.people().get(
    resourceName='people/me',
    personFields='emailAddresses'
).execute()

# 提取用户名(取邮箱@符号前的部分)
user_email = profile['emailAddresses'][0]['value']
user_name = user_email.split('@')[0]

print(f"当前Colab用户名:{user_name}")

首次运行时会弹出授权窗口,需用户允许访问个人信息,授权成功后即可获取用户名。

内容的提问来源于stack exchange,提问作者omri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:30:32