How To Convert XLSM File To XLSX Using Python

When working with Microsoft Excel files, you may encounter several file extensions, including .xls, .xlsx, and .xlsm. While .xls is an older format and .xlsx is the new format for Excel workbooks, the .xlsm format includes macro functionality, which can cause compatibility issues.

In this tutorial, we will show how to convert a .xlsm file to .xlsx using Python, allowing you to remove the macro components and maintain compatibility with other spreadsheets and applications.

Step 1: Install the necessary libraries

To get started, we need to ensure that the required Python libraries are installed. Those are openpyxl and xlsxwriter. You can install these packages using the commands below:

Step 2: Read the .xlsm file

We need to read the content of the .xlsm file using the openpyxl library. We will read the workbook and store it in a variable called xlsm_workbook:

Step 3: Create a new .xlsx file

Next, we will create a new .xlsx file using the xlsxwriter library and set up a new workbook in the file:

Step 4: Copy contents from .xlsm to .xlsx

Now that we have our source .xlsm file and our target .xlsx file, we need to copy the contents from the source file to the target file. To do this, we will iterate through each sheet in the xlsm_workbook and copy its contents to the corresponding sheet in the xlsx_workbook:

Step 5: Save and close the .xlsx file

Finally, we need to close and save the xlsx_workbook:

Full Code

Here’s the full code for your reference:

Conclusion

Now you know how to easily convert an .xlsm file to an .xlsx file using Python. This can be very useful when dealing with Excel files that contain macros, as they may not be compatible with other technologies or tools.

By converting the file to .xlsx, you can ensure that the file can be read and processed correctly by other applications.