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

如何通过URL借助Pandas获取电子表格的文件名?

获取Google表格文件名并导出为CSV

要获取Google表格的原始文件名,你无法直接通过pd.read_excel()或pd.ExcelFile()实现——因为导出的xlsx文件本身不会携带原表格名称。这里提供两种可行方案:

方案一:网页解析获取文件名(无需API密钥)

通过请求Google Sheets的网页,解析页面标题来提取原表格名称,步骤如下:

  1. 安装依赖库:
pip install requests beautifulsoup4
  1. 修改代码,添加文件名获取逻辑:
import pandas as pd
import requests
from bs4 import BeautifulSoup

link = input("Enter link here:")
link_parts = link.split('/')
sheet_id = link_parts[5]
print(sheet_id)

# 获取Google表格文件名
url = f"https://docs.google.com/spreadsheets/d/{sheet_id}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取标题并去掉末尾的" - Google Sheets"后缀
spreadsheet_name = soup.title.text.replace(" - Google Sheets", "")
print(f"表格文件名:{spreadsheet_name}")

# 读取工作表
xls = pd.ExcelFile(f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx")
sheet_1 = pd.read_excel(xls, "Summary", header=0)
print(sheet_1)
print("------------")

# 导出为CSV,用表格名+工作表名作为CSV文件名
csv_filename = f"{spreadsheet_name}_Summary.csv"
sheet_1.to_csv(csv_filename, index=False)
print(f"已导出CSV文件:{csv_filename}")

方案二:使用Google Sheets API(更稳定)

如果需要避免网页结构变化带来的解析失效,可以使用官方API:

  1. 前往Google Cloud控制台创建项目,启用Sheets API并获取API密钥
  2. 调用API获取表格信息:
import requests

API_KEY = "你的API密钥"
url = f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}?key={API_KEY}"
response = requests.get(url)
spreadsheet_data = response.json()
spreadsheet_name = spreadsheet_data["properties"]["title"]

这种方法可靠性更高,但需要完成API密钥的配置流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:27:12