How to convert .xlsm (macro enabled excel file) to .xlsx using Python?

Mahita picture Mahita · Sep 2, 2016 · Viewed 7.3k times · Source

I am trying to import data in an .xlsm file as a data frame. When I import the .xlsm file using the command below, it gives me an empty data frames as the result:

exp = pd.read_excel(File_Path+'file_name'.xlsx',sheetname='Data',header=None)

I have manually saved .xlsm files as .xlsx file and imported them as data frame.

Can anybody tell me how to save as .xlsm file as .xlsx using Python?

Answer

Martin Evans picture Martin Evans · Sep 5, 2016

I would suggest you try using a win32com type approach. If you are on Windows, you can use Python to automate Excel itself to carry out the conversion from an .xlxm file to .xlsx format. The file can then be read correctly using the usual Pandas pd.read_excel() function.

This can be done as follows:

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

# Load the .XLSM file into Excel
wb = excel.Workbooks.Open(r'input.xlsm')

# Save it in .XLSX format to a different filename
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(r"output.xlsx", FileFormat=51, ConflictResolution=2)
excel.Application.Quit()

# Load the .XLSX file into Pandas
df = pd.read_excel('output.xlsx', sheetname='Data', header=None)

I suggest you add full paths to the filenames.