我有一个长期运行的Python流水线,生成一个pandas数据框架。简而言之,我想
.xslx
挑战在于,我无法弄清楚如何做到这一点
没有一个中间的保存为
xlsm
的文件
步骤,这在向
.xlsx
文件添加VBA宏时显然是需要的。由于这样做效率很低,我想摆脱这个中间步骤。
Here is the code:
1.在excel中显示pandas数据框架。
with pd.ExcelWriter('output.xlsx') as writer:
df_results.to_excel(writer, index = False, sheet_name = "Sheet1")
#...see below
2A.添加宏并指定.xlsm-filename,以便编写者可以持有宏。
#... see above
writer.book.filename = 'output.xlsm' # Add .xlsm filename
writer.book.add_vba_project('VBA_script.bin') # This adds my macro
writer.save() # How to get rid of this step?
2B.运行宏
xl = win32com.client.Dispatch("Excel.Application") # Set up excel
xl.Workbooks.Open(Filename = 'output.xlsm') # Open .xlsm file from step 2A
xl.Application.Run("Module1.Main") # Run VBA_macro.bin
3.删除宏并保存为.xlsx
wb = xl.ActiveWorkbook
xl.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs('final_outfile.xlsx', FileFormat=51, ConflictResolution=2) # Macro disapears here
xl.Application.Quit()
del xl
xl = None
Is it possible to do this without intermediate .xlsm step & with shorter code?
How to add, run & remove a VBA macro in an excel context without intermediate saving steps using python?