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

我的梦境 提交于 2019-12-19 03:35:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39292179/how-to-convert-xlsm-macro-enabled-excel-file-to-xlsx-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!