如果您所需要做的只是启动 Excel,那么最好的方法是使用 LaunchServices 来执行此操作。
如果你有PyObjC
(如果您使用 Apple 在 10.6 及更高版本上预装的 Python,则需要执行此操作;否则,您可能需要安装它):
import Foundation
ws = Foundation.NSWorkspace.sharedWorkspace()
ws.launchApplication_('Microsoft Excel')
如果没有,您可以随时使用open
tool:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
无论哪种方式,您都可以有效地启动 Excel,就像用户双击 Finder 中的应用程序图标一样。
如果您想让 Excel 执行一些简单的操作(例如打开特定文档),那也并不困难。看着那(这NSWorkspace http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html or open https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/open.1.html文档来了解如何做你想做的事情。
如果你真的想controlExcel——例如,打开一个文档,进行一些更改,然后保存——您将需要使用它的 AppleScript 界面。
苹果推荐的方法是通过ScriptingBridge https://developer.apple.com/documentation/Cocoa/Conceptual/ScriptingBridgeConcepts/,或使用双语言方法(编写AppleScripts并通过NSAppleScript https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAppleScript_Class/Reference/Reference.html——在 Python 中,你可以通过PyObjC
)。但是,我可能会使用appscript http://appscript.sourceforge.net(从获取代码here https://github.com/abarnert/appscript)。尽管它已被其原始创建者放弃,并且仅得到稀疏维护,并且最终可能会停止与某些未来的 OS X 版本一起使用,但它仍然比官方解决方案要好得多。
这是一个示例(未经测试,因为我这里没有 Excel):
import appscript
excel = appscript.app('Microsoft Excel')
excel.workbooks[1].column[2].row[2].formula.set('=A2+1')