使用xlwings合并多个Excel工作簿时出现'list' object has no attribute 'lower'错误的求助
解决xlwings合并Excel时的AttributeError错误
嘿,这个错误其实很好排查,咱们一步步来拆解问题:
错误原因分析
第一个也是核心问题出在循环里的这一行:
wb = xw.Book(excel_files)
你把整个文件列表excel_files传给了xw.Book(),但xlwings的Book()构造函数需要的是单个Excel文件的路径,不是列表。当它尝试对这个列表调用字符串方法lower()(用来统一文件路径的大小写)时,自然就会抛出'list' object has no attribute 'lower'的错误——列表本身确实没有这个方法呀。
第二个是个小语法错误:
combined_wb.save(f("all_settlement_reports.xlsx"))
f-string的正确写法是用f""包裹内容,不是f(),这属于语法误用,得修正。
修正后的完整代码
from pathlib import Path import xlwings as xw print("enter file directory") SOURCE_DIR = input() excel_files = list(Path(SOURCE_DIR).glob("*.xlsx")) # 可选:添加空列表判断,避免后续无意义执行 if not excel_files: print("No Excel files found in the target directory!") exit() combined_wb = xw.Book() # 修正点1:传入循环变量excel_file(单个文件路径)而非整个列表 for excel_file in excel_files: wb = xw.Book(excel_file) for sheet in wb.sheets: sheet.api.copy(After=combined_wb.sheets[0].api) wb.close() combined_wb.sheets[0].delete() # 修正点2:修正f-string的语法错误 combined_wb.save(f"all_settlement_reports.xlsx") if len(combined_wb.app.books) == 1: combined_wb.app.quit() else: combined_wb.close()
额外小建议
- 你可以给输入的路径加个合法性判断,比如检查
Path(SOURCE_DIR).exists(),避免用户输入无效路径导致后续报错; - 如果目标文件夹里有打开需要密码的Excel文件,可能需要额外添加密码参数,但目前你的核心逻辑修正后就能正常运行啦。
内容的提问来源于stack exchange,提问作者Coakley
相关产品推荐
相关产品推荐

