How To Convert XLS To XLSX Using Python

In this tutorial, we will learn how to convert Excel files from .xls format to .xlsx format using Python.

This can be useful when you have older Excel files that need to be updated or when you need to work with files with different formats in a consistent manner. We will use the openpyxl and xlrd libraries to achieve this conversion.

Step 1: Install Required Libraries

Firstly, let’s install the required libraries for this conversion. You can install openpyxl and xlrd using pip by running the following commands:

Make sure you have these libraries successfully installed before moving forward.

Step 2: Import Required Libraries

Now, let’s import the required libraries into our Python script:

Step 3: Open the XLS File

We will now open the .xls file using the xlrd library. First, let’s specify the path to the .xls file:

Next, we will open the .xls file using the xlrd.open_workbook function:

Now that we have opened the .xls file, we can proceed to create a new .xlsx file that will contain the data from the .xls file.

Step 4: Convert XLS to XLSX

To convert the data from the .xls file to the .xlsx file, we’ll create a new openpyxl Workbook object and copy the contents of the .xls file into it:

Here, we are iterating through all sheets in the .xls file, and for each sheet, we are iterating through all rows and columns to copy cell values from the .xls file to the .xlsx file.

Step 5: Save the XLSX File

Now that all the data from the .xls file has been copied to the .xlsx file, we can save the .xlsx file with the same name but with the .xlsx extension:

Your .xls file should now be successfully converted into .xlsx format.

Full Code:

Conclusion

In this tutorial, we learned how to convert Excel files from .xls to .xlsx format using the openpyxl and xlrd libraries in Python. This method can be helpful when working with Excel files of different formats and updating older files to a more recent format. Happy converting!