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

使用pd.ExcelWriter时代码跳转至函数末尾,报错IndexError求助

问题

有一个使用Pandas的ExcelWriter导出数组到Excel的函数,正常运行多年后突然异常:执行到with pd.ExcelWriter(excelpath) as exwriter后,仅运行format_link = exwriter.book.add_format()就跳过所有中间代码(条件判断、循环等)直接到函数末尾,触发报错IndexError: At least one sheet must be visible。

环境:PyCharm 2023.3.2社区版,Python 3.9.13

函数代码:

def make_excel_array(the_array, headings, file_name, path="/Users/jrfreeze/Documents/DS_data/",
                     tab="Sheet1", col_format=True, color_rows=()):
    """
    Accepts array of data and headings for excel sheet, exports excel workbook
    :param the_array: list or lists of data
    :param headings: list of the excel columns, send 0 or "" or [] to ignore
    :param file_name: string desired name of the excel file
    :param tab: string name on tab
    :param path: string directory to pace the Excel file
    :param col_format: boolean format column width to widest entry up to max of 50
    :param color_rows: tuple of tuple of tuple and str. One middle tuple for each set of rows to color.
                    Inner tuple is row numbers to color; str is color to apply; e.g. (((1,2), 'red'), ((3,4), 'blue))
    :return:
    """
    import inspect
    excelpath = path + file_name + ".xlsx"
    if headings:
        df = pd.DataFrame(the_array, columns=headings)
    else:
        df = pd.DataFrame(the_array)
    if col_format:
        max_lens = get_max_lens(the_array, headings)
    else:
        max_lens = []
    with pd.ExcelWriter(excelpath) as exwriter:
        format_link = exwriter.book.add_format()
        format_link.set_font_color('blue')
        if headings:
            df.to_excel(exwriter, sheet_name=tab, index=False)
        else:
            df.to_excel(exwriter, sheet_name=tab, index=False, header=False)
        worksheet = exwriter.sheets[tab]
        caller = inspect.currentframe().f_back.f_code.co_name
        if caller == "get_lsdyna_user_jobs":
            worksheet.write(1, 1, df.iloc[0, 1], format_link)
            worksheet.write(1, 2, df.iloc[0, 2], format_link)
        if col_format:
            for i in range(len(max_lens)):
                worksheet.set_column(i, i, max_lens[i])
        if color_rows:
            for rows_format in color_rows:
                row_color = exwriter.book.add_format()
                row_color.set_font_color(rows_format[1])
                for row in rows_format[0]:
                    worksheet.set_row(row, None, row_color)

调用示例:

array = [['abd', 1], ['def', 2]]
headers = ['letters', 'number']
excelpath = '/Users/jrfreeze/Documents/DS_Quarterly_Reports/PY4_Q1/'
filename = 'testsheet'
make_excel_array(array, headers, filename, path=excelpath)

用户尝试注释掉if color_rows代码块后问题依旧,推测df.to_excel()未执行,但不清楚代码跳转原因,需要解决思路。


解决思路

  • 排查版本兼容性问题:这个报错常见于Pandas与Excel写入引擎(如openpyxl)版本不兼容。函数之前正常运行,大概率是近期升级了Pandas或openpyxl导致冲突。可以回退到之前稳定的版本,或者显式指定写入引擎测试:pd.ExcelWriter(excelpath, engine='openpyxl')。
  • 捕获未处理的异常:代码执行到add_format()后跳转,大概率是后续代码抛出了未被捕获的异常,导致with块提前退出。在with块内添加异常捕获,打印详细错误信息:
    with pd.ExcelWriter(excelpath) as exwriter:
        try:
            format_link = exwriter.book.add_format()
            format_link.set_font_color('blue')
            # 后续所有代码缩进进try块
            if headings:
                df.to_excel(exwriter, sheet_name=tab, index=False)
            else:
                df.to_excel(exwriter, sheet_name=tab, index=False, header=False)
            worksheet = exwriter.sheets[tab]
            # ... 其余代码
        except Exception as e:
            print(f"错误详情: {e}")
            import traceback
            traceback.print_exc()
    
  • 检查exwriter.book的API兼容性:add_format()是xlwt引擎的方法,如果当前使用的是openpyxl引擎(默认处理.xlsx文件),调用这个方法会直接抛出AttributeError,导致代码跳转。需要根据使用的引擎调整格式设置代码:openpyxl用Style相关API而非add_format()。
  • 验证文件路径权限:确认目标路径excelpath存在且当前用户有写入权限,权限不足会导致df.to_excel()执行失败,异常被with块的上下文管理器吞掉,最终触发无可见工作表的报错。
  • 隔离get_max_lens函数影响:临时注释掉max_lens相关代码,如果问题消失,说明get_max_lens函数抛出了未被捕获的异常,需要排查该函数的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:32:06