如何在python中使用xlrd和openpyxl库将xls excel文件转换为xlsx文件

问题描述 投票:0回答:1

我尝试了以下代码,使用Python中的xlrd和openpyxl库将xls excel文件转换为xlsx文件,因为openpyxl不读取xls文件。

import xlrd
import openpyxl


excel_files = ['one.xls', 'two.xls', 'three.xls', 'four.xls', 'five.xls', 'six.xls']


for excel_file in excel_files:

    
    wb_old = xlrd.open_workbook(excel_file)

    
    wb_new = openpyxl.Workbook()

    
    ws_new = wb_new.active
    for ws_old in wb_old.sheets():
        for row in range(ws_old.nrows):
            for col in range(ws_old.ncols):
                ws_new.cell(row=row, column=col).value = ws_old.cell(row=row, column=col).value

    
    wb_new.save(excel_file.replace('.xls', '.xlsx'))

问题是我收到以下错误:TypeError: cell() gets an Unexpected keywords argument 'row'。这个错误是参考这行代码:

ws_new.cell(row=row, column=col).value = ws_old.cell(row=row, column=col).value

有人可以帮我解决这个问题吗?

python openpyxl xlrd
1个回答
0
投票

代码中的行

ws_new.cell(row=row, column=col).value = ws_old.cell(row=row, column=col).value

有两个原因无效;

  1. Xlrd 不使用 'row=' 和 'col=',您只需在括号中添加行和列坐标,如 (0, 0)。
  2. Openpyxl 行数和列数从 1 开始,而 xlrd 从 0 开始。因此,在第一次迭代时,Openpyxl 单元格中
    row=
    col=
    的值将失败。

您需要将该行更改为类似这样的内容;

ws_new.cell(row=row+1, column=col+1).value = ws_old.cell(row, col).value
© www.soinside.com 2019 - 2024. All rights reserved.