如何通过Python将CSV上传至Google Spreadsheet新建工作表
实现方法
gspread本身自带新建工作表的方法,不需要额外对接其他API,直接修改现有代码即可。核心是调用spreadsheet.add_worksheet()方法在当前电子表格下创建新标签页,再把CSV内容写入这个新页。
修改后完整代码
import csv from datetime import date import gspread from oauth2client.service_account import ServiceAccountCredentials scope = [ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ] credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) client = gspread.authorize(credentials) # 打开要上传的目标电子表格 spreadsheet = client.open("abc") # --- 新工作表命名规则 二选一即可 --- # 规则1(推荐):用上传当天日期命名,不会重名,后续回溯每日数据更方便 new_sheet_name = f"CSV数据_{date.today().strftime('%Y-%m-%d')}" # 规则2:按需求顺延命名,首个标签页叫CSV-to-Google-Sheet,之后依次是sheet1、sheet2... # existing_sheets = spreadsheet.worksheets() # if not existing_sheets: # new_sheet_name = "CSV-to-Google-Sheet" # else: # new_sheet_name = f"sheet{len(existing_sheets)}" # 读取CSV内容,提前计算需要的行列数 with open('123.csv', 'r', encoding='utf-8') as f: csv_content = list(csv.reader(f)) total_rows = len(csv_content) total_cols = max(len(row) for row in csv_content) if csv_content else 1 # 创建新的工作表 new_worksheet = spreadsheet.add_worksheet( title=new_sheet_name, rows=total_rows, cols=total_cols ) # 把CSV内容写入新建的标签页 new_worksheet.append_rows(csv_content, value_input_option="USER_ENTERED")
注意事项
- 提前确认使用的服务账号已经被添加为目标电子表格的协作者,且拥有编辑权限,否则新建、写入操作都会报错
- 读取CSV时显式指定
encoding='utf-8'可以避免Windows环境下读取中文内容乱码,如果CSV是其他编码,改成对应编码值即可 - 新建工作表时传入的行列数是初始值,后续写入内容超出范围时会自动扩容,不需要严格卡准数值
- 要实现每日自动运行,把脚本挂到服务器定时任务即可(比如Linux的crontab、Windows的任务计划程序),不需要额外调整代码逻辑
你提到的标签页效果参考:
内容的提问来源于stack exchange,提问作者TryingToLearnSomething
相关产品推荐
相关产品推荐

