Python读取Excel遇TypeError与AttributeError的解决问询
解决读取Excel文件时的TypeError和AttributeError问题
错误原因分析
第一个错误:TypeError: 'list' object is not callable
workbook.sheet_names是一个列表,存储了Excel文件中所有工作表的名称,不能像函数一样通过(0)调用。用索引sheet_names[0]能获取第一个工作表的名称,但这只是字符串,不是可操作的工作表对象。
第二个错误:AttributeError: 'str' object has no attribute 'rows'
sh=workbook.sheet_names[0]得到的是字符串类型的工作表名称,而非实际的工作表对象,因此它不具备rows、ncols、cell_value()这类属性和方法。
修正后的代码方案
方案一:用pandas库实现(推荐,处理Excel更简洁)
直接将工作表读取为DataFrame,再逐行写入文本文件:
import pandas as pd # 读取第一个工作表为DataFrame df = pd.read_excel(r'C:\Users\engel\Documents\python\docs\Book1.xlsx', engine='openpyxl', sheet_name=0) # 写入txt文件,用with语句自动管理文件资源 with open("xxx.txt", "w", encoding="utf-8") as file: for _, row in df.iterrows(): # 将行数据转为空格分隔的字符串 line = " ".join(str(cell) for cell in row.values) print(line) file.write(line + "\n")
方案二:用xlrd库实现(注意版本兼容)
xlrd 2.0及以上版本仅支持.xls格式,若处理.xlsx需使用旧版本xlrd,或改用openpyxl:
import xlrd # 用xlrd打开Excel文件 workbook = xlrd.open_workbook(r'C:\Users\engel\Documents\python\docs\Book1.xlsx') # 获取第一个工作表对象 sh = workbook.sheet_by_index(0) with open("xxx.txt", "w", encoding="utf-8") as file: for n in range(sh.nrows): line_content = "" for i in range(sh.ncols): data = str(sh.cell_value(n, i)) + " " line_content += data # 移除末尾多余空格后打印并写入 cleaned_line = line_content.strip() print(cleaned_line) file.write(cleaned_line + "\n")
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

