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

使用gspread实现“BOT: output”工作表不存在则创建,解决重复执行报错

问题解决:重复创建工作表报错的异常处理修正

你的代码问题在于捕获的异常类型不正确,notFound不是任何Python标准库或表格操作库的内置异常类,导致异常无法被正确捕获。

修正步骤

1. 确认使用的库对应的正确异常类型

不同表格操作库抛出的“工作表不存在”异常不同:

  • 使用gspread(谷歌表格API):异常类为gspread.exceptions.WorksheetNotFound
  • 使用openpyxl:异常为KeyError
  • 使用xlwings:异常为ValueError

2. 修改后的代码示例

示例1:gspread库

from gspread.exceptions import WorksheetNotFound

try:
    wks2 = mySheet.worksheet("BOT: output")
except WorksheetNotFound:
    # add_worksheet参数需对应库要求,gspread中是title、rows、cols
    wks2 = mySheet.add_worksheet(title="BOT: output", rows=999, cols=20)

示例2:openpyxl库

try:
    wks2 = mySheet["BOT: output"]
except KeyError:
    wks2 = mySheet.create_sheet(title="BOT: output")
    # 调整工作表最大行列数
    wks2.max_row = 999
    wks2.max_column = 20

3. 排查未知异常的方法

如果不确定具体异常类型,可以先临时捕获通用异常来查看:

try:
    wks2 = mySheet.worksheet("BOT: output")
except Exception as e:
    print(type(e), str(e))  # 打印异常类型和信息,再替换成具体异常类
    wks2 = mySheet.add_worksheet("BOT: output", "999", "20")

内容的提问来源于stack exchange,提问作者Abdullah Al Shehri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:30:52