在Python中,你可以用COM/ActiveX做什么?

39

我已经阅读过,可以使用COM/ActiveX在Crystal Reports中自动化生成月度报告。我并不太了解这是什么,或者它能用来做什么。

我还经常使用Excel进行工作,看起来您也可以使用COM/ActiveX与之交互。

请问是否有人可以解释一下这是怎么工作的,并可能提供一个简短的例子?


你也可以在这里找到有用的技巧: http://timgolden.me.uk/python/win32_how_do_i.html 它很容易适应任何类型的应用程序。 - user84491
4个回答

43

首先,您需要安装神奇的pywin32模块。

它提供了COM支持。您需要运行makepy实用程序。它位于C:\ ... \ Python26 \ Lib \ site-packages \ win32com \ client。在Vista上,必须以管理员权限运行。

此实用程序将显示所有可用的COM对象。您可以找到您需要的对象并为其生成Python包装器。

包装器是在C:\ ... \ Python26 \ Lib \ site-packages \ win32com \ gen_py文件夹中生成的Python模块。该模块包含COM对象的接口。文件名是COM唯一ID。如果您有多个文件,则有时很难找到正确的文件。

之后,您只需调用正确的接口即可。这是非常神奇的 :)

以下是一个关于Excel的简短示例:

import win32com.client

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible=1

workBook = xlApp.Workbooks.Open(r"C:\MyTest.xls")
print str(workBook.ActiveSheet.Cells(i,1))
workBook.ActiveSheet.Cells(1, 1).Value = "hello"                
workBook.Close(SaveChanges=0) 
xlApp.Quit()

1
如果您收到有关未注册事项的错误,请确保在使用32位com对象时使用32位Python。http://python.6.x6.nabble.com/Problem-using-win32com-client-Dispatch-on-Win7-64bit-td1957248.html - Gourneau
不需要"import pythoncom" - user327843
我修复了“import pythoncom”不是必需的。 - luc

4

你基本上可以执行与延迟绑定等效的操作。因此,通过IDispatch公开的任何内容都可以被消耗。

这是我上周末编写的一些代码,用于通过Windows图像采集2.0从twain设备获取图像,并将数据放入可以插入gtk基​​础UI的东西中。

WIA_COM = "WIA.CommonDialog"
WIA_DEVICE_UNSPECIFIED = 0
WIA_INTENT_UNSPECIFIED = 0
WIA_BIAS_MIN_SIZE = 65536
WIA_IMG_FORMAT_PNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}"

def acquire_image_wia():
    wia = win32com.client.Dispatch(WIA_COM)
    img = wia.ShowAcquireImage(WIA_DEVICE_UNSPECIFIED,
                           WIA_INTENT_UNSPECIFIED,
                           WIA_BIAS_MIN_SIZE,
                           WIA_IMG_FORMAT_PNG,
                           False,
                           True)
    fname = str(time.time())
    img.SaveFile(fname)
    buff = gtk.gdk.pixbuf_new_from_file(fname)
    os.remove(fname)

return buff

虽然不太美观,但它确实有效。我认为这与你在VB中所需编写的代码是等效的。


3

这里是一个可行的解决方案,它创建一个文件并向单元格添加值:

import win32com.client
import xlsxwriter
import os
cwd = os.getcwd()
file_path = cwd + "\\test.xlsx"

#Create an excel file
workbook = xlsxwriter.Workbook(file_path)
worksheet = workbook.add_worksheet()
workbook.close()

#Open an excel application
xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible=1


workBook = xlApp.Workbooks.Open(file_path)
print str(workBook.ActiveSheet.Cells(1,1))
workBook.ActiveSheet.Cells(1, 1).Value = "hello55"                
workBook.Close(SaveChanges=1) 
xlApp.Quit()

1
如何在Python 3中接收ActiveX事件
# coding=utf8

from PyQt5.QAxContainer import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QObject
import sys

TITLE = "CallX Python Example: accept any calls"
TrueConfCallX_Class = '{27EF4BA2-4500-4839-B88A-F2F4744FE56A}'

SERVER = '' # empty - connect to TrueConf Online cloud
USER = '<trueconf id>'
PASSWORD = '<password>'

class CallXWindow(QWidget):

    def __init__(self):
        QAxWidget.__init__(self)
        self.setWindowTitle(TITLE)
        self.move(400, 30)
# end of class CallXWindow(QWidget)


class ActiveXExtend(QObject):

    def __init__(self, view):
        super().__init__()
        self.view = view
        self.ocx = QAxWidget(TrueConfCallX_Class)

        self.ocx.move(0, 0)
        self.ocx.setFixedSize(640, 375)
        self.ocx.setParent(self.view)
        self.ocx.show()

        # receive some ActiveX events 
        self.ocx.OnXAfterStart.connect(self._OnXAfterStart)
        self.ocx.OnServerConnected[str].connect(self._OnServerConnected)
        self.ocx.OnLogin[str].connect(self._OnLogin)
        self.ocx.OnInviteReceived[str].connect(self._OnInviteReceived)
        self.ocx.OnXError[int, str].connect(self._OnXError)
        self.ocx.OnXLoginError[int].connect(self._OnXLoginError)

    # Events
    def _OnXAfterStart(self):
        print("**OnXAfterStart")
        # select devices
        self.ocx.XSetCameraByIndex(0)
        self.ocx.XSelectMicByIndex(0)
        self.ocx.XSelectSpeakerByIndex(0)
        # connect to server
        self.ocx.connectToServer(SERVER)

    def _OnServerConnected(self, eventDetails):
        print("**OnServerConnected")
        print(eventDetails)
        # login
        self.ocx.login(USER, PASSWORD)

    def _OnLogin(self, eventDetails):
        print("**OnLogin")

    def _OnInviteReceived(self, eventDetails):
        print("**OnInviteReceived")
        print(eventDetails)
        # accept any calls
        self.ocx.accept()

    def _OnXError(self, errorCode, errorMsg):
        print("**OnXError")
        print('{}. Code: {}'.format(errorMsg, errorCode))

    def _OnXLoginError(self, errorCode):
        print("**OnXLoginError")
        if errorCode == 8:
            print('Support for SDK Applications is not enabled on this server')
        else:
            print('Login error. Code: {}'.format(errorCode))
# end of class ActiveXExtend(QObject)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = CallXWindow()
    axwin = ActiveXExtend(MainWindow)
    MainWindow.show()
sys.exit(app.exec_())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接