简体   繁体   English

如何使用Python将.xlsm(支持宏的excel文件)转换为.xlsx?

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

I am trying to import data in an .xlsm file as a data frame. 我试图将.xlsm文件中的数据导入为数据框。 When I import the .xlsm file using the command below, it gives me an empty data frames as the result: 当我使用下面的命令导入.xlsm文件时,它会给我一个空数据帧作为结果:

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. 我手动将.xlsm文件保存为.xlsx文件并将其作为数据框导入。

Can anybody tell me how to save as .xlsm file as .xlsx using Python? 任何人都可以告诉我如何使用Python将.xlsm文件保存为.xlsx?

I would suggest you try using a win32com type approach. 我建议你尝试使用win32com类型的方法。 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. 如果您使用的是Windows,则可以使用Python自动执行Excel本身,以执行从.xlxm文件到.xlsx格式的转换。 The file can then be read correctly using the usual Pandas pd.read_excel() function. 然后可以使用通常的Pandas pd.read_excel()函数正确读取该文件。

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. 我建议你添加文件名的完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM