使用python在xlsm中运行宏

时间:2014-01-20 14:53:03

标签: python excel csv

我有一个基本要求。

我有一个.csv文件和一个有宏的.xlsm文件。我需要将.csv文件的内容复制到该.xlsm文件并运行宏。我需要使用Python。

是否有任何脚本可以实现此目的?

提前致谢。

2 个答案:

答案 0 :(得分:1)

file_dir = os.path.dirname(import_file_path) 
filename = 'sample.xlsx' 
writer = pd.ExcelWriter(filename, engine='xlsxwriter')#Write excel file after write data.(only for write temporary data.)
df.to_excel(writer, sheet_name='ResultSet', index=False)
# ATTACH MACRO AND CREATE .XLSM FILE#
filename_macro =  'sample.xlsm'#Create Macro File.
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()
if os.path.exists("sample.xlsm"):#Check file
    xl = win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath("sample.xlsm"))
   xl.Application.Quit() # Comment this out if your excel script closes
    del xl


    if os.path.exists( 'ResultSet1.xlsx'):#checked file exit or not
        # Make duplicate file in user selected directory
        xl1 = load_workbook(filename= 'ResultSet1.xlsx')
        xl1.save('ResultSet.xlsx')

答案 1 :(得分:0)

此链接应该有助于通过python打开XLSM并填充数据... Python, Excel, and Charts using win32com

这个展示了如何运行宏 Python - run Excel macro

相关问题