从Python访问Microsoft自动化对象

2024-05-15 14:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组宏,已在excel中转换为外接程序。宏允许我与另一个程序交互,该程序具有称为Microsoft Automation对象的对象,这些对象提供了对另一个程序所做操作的一些控制。例如,我在外接程序中有一个筛选工具,用于筛选其他程序提供的列表,以匹配Excel工作簿中的列表。不过这很慢。我可能在另一个程序中有5万行,并且希望筛选出所有与Excel中3000行列表不匹配的行。这种匹配大约需要30-40分钟。我开始怀疑是否有办法用Python来代替它,因为我怀疑匹配过程可以在几秒钟内完成。

编辑:

谢谢——根据看哈蒙德的书的建议,我找到了一些资料。不过,虽然我还在探索,但看起来很多都已经过时了。例如,哈蒙德的书是在2000年出版的,这意味着这本书差不多在十年前就写完了。更正我刚找到一个名为PyWin32的包,它有一个2/2009版本。

这应该让我开始。谢谢


Tags: 工具对象程序编辑列表过程excel建议
3条回答

您可能需要win32com包。

这是我在:http://www.markcarter.me.uk/computing/python/excel.html找到的一个示例,它展示了如何在Excel中使用com。这也许是个好的开始。

# this example starts Excel, creates a new workbook, 
# puts some text in the first and second cell
# closes the workbook without saving the changes
# and closes Excel.  This happens really fast, so
# you may want to comment out some lines and add them
# back in one at a time ... or do the commands interactively


from win32com.client import Dispatch


xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp

# raw_input("press Enter ...")

据我所知,可以在Windows上用Python创建COM对象(这就是自动化对象)。然后假设您可以通过自动化获得列表,那么在python中做您想要的事情应该很容易。

Mark Hammond和Andy Robinson已经编写了the book关于从Python访问Windows COM对象。

Here是一个使用Excel的例子。

相关问题 更多 >