What can you do with COM/ActiveX in Python? [closed]
Asked Answered
V

4

39

I've read that it is possible to automate monthly reports in Crystal Reports with COM/ActiveX. I'm not that advanced to understand what this is or what you can even do with it.

I also do a lot of work with Excel and it looks like you also use COM/ActiveX to interface with it.

Can someone explain how this works and maybe provide a brief example?

Vibes answered 30/6, 2009 at 20:24 Comment(1)
You can also find useful tips here : timgolden.me.uk/python/win32_how_do_i.html it's easy to adapt to any kind of application.Allhallows
A
43

First you have to install the wonderful pywin32 module.

It provides COM support. You need to run the makepy utility. It is located at C:\...\Python26\Lib\site-packages\win32com\client. On Vista, it must be ran with admin rights.

This utility will show all available COM objects. You can find yours and it will generate a python wrapper for this object.

The wrapper is a python module generated in the C:\...\Python26\Lib\site-packages\win32com\gen_py folder. The module contains the interface of the COM objects. The name of the file is the COM unique id. If you have many files, it is sometimes difficult to find the right one.

After that you just have to call the right interface. It is magical :)

A short example with 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()
Afternoons answered 1/7, 2009 at 7:59 Comment(3)
If you are getting errors about things not being registered, make sure you are using 32 bit Python if you are using 32 bit com objects. python.6.x6.nabble.com/…Quincyquindecagon
"import pythoncom" is not requiredCarbrey
I fixed the "import pythoncom" is not requiredAfternoons
A
4

You can basically do the equivalent of late binding. So whatever is exposed through IDispatch is able to be consumed.

Here's some code I wrote this weekend to get an image from a twain device via Windows Image Acquisition 2.0 and put the data into something I can shove in a gtk based 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

It's not pretty but it works. I would assert it's equivalent to what you would have to write in VB.

Aquiculture answered 30/6, 2009 at 22:21 Comment(0)
C
3

Here is a working solution that creates a file and adds value to a cell:

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()
Cosmotron answered 19/9, 2017 at 13:49 Comment(0)
P
1

How to receive ActiveX events in python 3

# 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_())
Portion answered 5/12, 2018 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.