1 回答
TA贡献1846条经验 获得超7个赞
因为.xlsxto.xlsm是根本不同类型的二进制文件,所以不能简单地使用行复制和重命名:
shutil.copy("normal_excel_file.xlsx", "(1)normal_excel_file.xlsx")
os.rename("(1)normal_excel_file.xlsx", "macros_excel_file.xlsm")
(奇怪的是,您的教程链接没有显示 Pandas 生成的.xlsx文件.xlsm在后续附加的宏步骤中是如何变成的。)
相反,使用 Excel 编写器对象来迁移宏并另存为.xlsm. 此外,在编写器对象上使用上下文with管理器在处理后有效地关闭 i/o 对象。
# creating the dataframe
path = "C:\Users\John\Desktop\Python_scripts\Running VBA Macro"
filename = "normal_excel_file.xlsx"
filename_macro = "macros_excel_file.xlsm"
df = pd.read_excel(filename, index_col=0)
with pd.ExcelWriter(filename, engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='data', index=False)
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()
# RUN MACRO
if os.path.exists(os.path.join(path, filename_macro)):
wb = xl.Workbooks.Open(Filename = filename_macro, ReadOnly=1)
xl.Application.Run("ThisWorkbook.Macro1")
xl.Application.Quit()
添加回答
举报