How to convert xls excel files to xlsx files using xlrd and openpyxl libraries in python

211 views Asked by At

I have tried the following code to convert xls excel files to xlsx files using xlrd and openpyxl libraries in python since openpyxl does not read xls files.

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'))

The problem is that I get the following error: TypeError: cell() got an unexpected keyword argument 'row'. This error is in reference to this line of code: ws_new.cell(row=row, column=col).value = ws_old.cell(row=row, column=col).value

Can someone help me on how to fix this?

1

There are 1 answers

1
moken On

The line in your code

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

causes issues for two reasons;

  1. Xlrd doesn't use 'row=' & 'column=', you just add the row and column co-ordinate in brackets like (0, 0). This is the cause of the error message you see.
  2. Openpyxl row and column counts start at 1 while xlrd starts at 0. Therefore on your first iteration the values for row= and column= in the Openpyxl cell being 0 will fail.

You'd need to change that line to something like this;

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