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

合并多个Excel文件时出现NameError: name 'filenames' is not defined错误求助

问题排查与修正方案

1. 直接触发NameError的原因

你在print('File names:', filenames)里用了变量filenames,但实际定义的变量名是excel_files,两者不匹配,这就是报错的直接原因。把filenames改成excel_files即可。

2. 其他潜在问题及修复

  • 缺少xlwings导入:代码里用了xw.App,但没有导入xlwings库,需要添加import xlwings as xw,同时确保已安装xlwings(执行pip install xlwings)。
  • 路径转义问题:Windows路径中的反斜杠\需要转义,或使用原始字符串避免\e等被解析为转义字符。比如把path = "T:\excel_Report"改成path = r"T:\excel_Report"。
  • 冗余代码:定义了outputxlsx = pd.DataFrame()但未使用,可直接删除。
  • 空白工作表清理:合并后的工作簿会自带一个空白工作表,建议取消注释combined_wb.sheets[0].delete(),移除多余的默认表。

修正后的完整代码

import pyodbc
import pandas as pd
import os
from datetime import datetime
from plyer import notification
import glob
import xlwings as xw  # 新增xlwings导入

# 使用原始字符串避免路径转义问题
path = r"T:\excel_Report"

# 读取所有.xlsx文件
excel_files = glob.glob(path + r"\*.xlsx")
print('File names:', excel_files)  # 修正变量名

with xw.App(visible=False) as app:
    combined_wb = app.books.add()
    for excel_file in excel_files:
        wb = app.books.open(excel_file)
        for sheet in wb.sheets:
            sheet.copy(after=combined_wb.sheets[0])
        wb.close()
    # 删除默认的空白工作表
    combined_wb.sheets[0].delete()
    combined_wb.save(r"T:/excel_Report/test.xlsx")
    combined_wb.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:55:59