使用xlrd与openpyxl转XLS为XLSX遇TypeError报错,求解决
问题修复方案
报错原因
- xlrd参数不匹配:xlrd的
cell()方法不支持row/column作为关键字参数,它的参数为rowx(行索引)和colx(列索引),或直接传入位置值。 - 索引起始值差异:openpyxl的单元格索引从1开始,而xlrd从0开始,直接复用索引会导致数据偏移。
- 工作表逻辑错误:原代码将所有旧工作表的数据写入新工作簿的默认工作表,会造成数据覆盖。
修复后的代码
import xlrd import openpyxl excel_files = ['one.xls', 'two.xls', 'three.xls', 'four.xls', 'five.xls', 'six.xls'] for excel_file in excel_files: # 读取旧XLS文件 wb_old = xlrd.open_workbook(excel_file) # 创建新XLSX工作簿 wb_new = openpyxl.Workbook() # 删除默认生成的空工作表 wb_new.remove(wb_new.active) # 遍历每个旧工作表 for ws_old in wb_old.sheets(): # 创建同名新工作表 ws_new = wb_new.create_sheet(title=ws_old.name) # 逐行逐列复制数据 for row in range(ws_old.nrows): for col in range(ws_old.ncols): # xlrd用位置参数取单元格,openpyxl索引+1适配1起始规则 ws_new.cell(row=row+1, column=col+1).value = ws_old.cell(row, col).value # 保存转换后的文件 wb_new.save(excel_file.replace('.xls', '.xlsx'))
关键修改点
- xlrd单元格读取:将
ws_old.cell(row=row, column=col)改为ws_old.cell(row, col)(位置参数),或ws_old.cell(rowx=row, colx=col)(正确关键字参数)。 - openpyxl索引修正:行、列索引均加1,适配openpyxl从1开始的索引规则。
- 工作表对应创建:删除默认空工作表,为每个旧工作表创建同名新工作表,避免数据覆盖。
内容的提问来源于stack exchange,提问作者dmoney21
相关产品推荐
相关产品推荐

