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

如何在gspread中新建工作表并上传本地CSV文件

解决gspread将本地CSV导入现有表格新工作表的问题

核心思路:绕开会覆盖原有工作表的import_csv方法,先创建新工作表,再将CSV数据写入该表。

完整实现代码

import gspread
import csv
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials

# 认证(根据你的认证方式调整,示例为服务账号认证)
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('你的服务账号JSON文件路径.json', scope)
client = gspread.authorize(creds)

# 打开目标现有表格
spreadsheet = client.open('你的表格名称')

# 创建以当日日期命名的新工作表(行数、列数可按需调整)
today_date = datetime.now().strftime('%Y-%m-%d')
new_worksheet = spreadsheet.add_worksheet(title=today_date, rows="1000", cols="20")

# 读取本地CSV文件内容
csv_path = '你的本地CSV文件路径.csv'
with open(csv_path, 'r', encoding='utf-8') as f:
    csv_data = list(csv.reader(f))

# 批量写入数据到新工作表
new_worksheet.update(csv_data)

补充优化说明

  • 避免同名工作表报错:如果担心当日工作表已存在,可先检查再处理:
existing_sheet_titles = [sheet.title for sheet in spreadsheet.worksheets()]
if today_date not in existing_sheet_titles:
    new_worksheet = spreadsheet.add_worksheet(title=today_date, rows="1000", cols="20")
else:
    new_worksheet = spreadsheet.worksheet(today_date)
    new_worksheet.clear()  # 可选:清空原有内容后重新写入
  • 认证方式替换:若使用OAuth2授权码认证,替换对应认证代码即可,无需修改核心逻辑。
  • 大文件处理:如果CSV文件过大,可拆分数据分批次写入,避免超时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:18:37