IronPython - Run an Excel Macro

六月ゝ 毕业季﹏ 提交于 2019-12-23 16:34:24

问题


I'm running TIBCO Spotfire v4. It has IronPython built in. Looking to run a Spotfire report that will export a .xls file (that part is done). Looking for a script to open an Excel file and run a macro to be able to format the file.

Here's some code I found and tried using. Not sure where the import items come from!

import os, os.path, win32com.client

def run_macro(fName, macName, path=os.getcwd()):
    """ 
    pre: fName is the name a valid Excel file with macro macName
    post: fName!macName is run, fName saved and closed
    """ 
    fName = os.path.join(path, fName) 
    xlApp = win32com.client.Dispatch("Excel.Application") 
    fTest = xlApp.Workbooks.Open(fName) 
    macName = fTest.Name + '!' + macName xlApp.Run(macName) 
    fTest.Close(1)
    xlApp.Quit() 
    xlApp = None

EDITOR - Code looks to be from Cannot iterate VBA macros from Python.


回答1:


I had a similar problem (trying to run an Excel VBA Macro from ipy), and ended up getting it working.

Try this code:

# .net access
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")

# opening the workbook
excel = Excel.ApplicationClass()   
excel.Visible = True
excel.DisplayAlerts = False   
workbook = excel.Workbooks.Open(r"C:\your\file\here.xls")
# or open locally:
# workbook = ex.Workbooks.Open('here.xls')

# running the macro
excel.Run('YOUR-MACRO-NAME')

# closing down
excel.Exit()

The first section is using .NET , and the second part is actually executing the macro. Note that this is to run excel code from a excel file that is not open. If you want to run a macro from a file that is already open (which something I also had to do, so figured I may as well put in here), you would need to recognize it as an active object instead of opening it (see below). The code to run the macro would still be the same as above.

# recognizing an already opened window
from System.Runtime.InteropServices import Marshal
excel = Marshal.GetActiveObject("Excel.Application")

This link was very useful when I was looking for a solution:

http://www.ironpython.info/index.php?title=Interacting_with_Excel



来源:https://stackoverflow.com/questions/17411911/ironpython-run-an-excel-macro

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