Using Python to Automate Visio
There are lots of examples of automating office apps out there but Visio examples seem thin on the ground. I guess this is partly due to its relatively recent inclusion into the Office fold. The example below shows Visio code to create a diagram with two rectangles joined by a connector. Its written in Python and makes use of the win32com package provided by pywin32. This is installed by default with ActivePython. I had some difficulty getting the makepy tool to see the Microsoft Visio 11.0 Type Library that showed up fine as a registered object in Visual Studio and Excel/VBA. In the end I had to explicitly point makepy at the VISLIB.DLL. That said the code below will work fine without this step as I don't make use of any of the Visio Constants.
import os import win32com.client # Two lines below generated from the command: # python makepy.py -i VISLIB.DLLfrom win32com.client import gencache gencache.EnsureModule('{00021A98-0000-0000-C000-000000000046}', 0, 4, 11) from win32com.client import constants appVisio = win32com.client.Dispatch("Visio.Application") appVisio.Visible =1 doc = appVisio.Documents.Add("Basic Diagram.vst") pagObj = doc.Pages.Item(1) stnObj = appVisio.Documents("Basic Shapes.vss") mastObj = stnObj.Masters("Rectangle") shpObj1 = pagObj.Drop(mastObj, 4.25, 5.5) shpObj1.Text = "This is some text." shpObj2 = pagObj.Drop(mastObj, 2, 2) shpObj2.Text = "This is some more text." connectorMaster = appVisio.Application.ConnectorToolDataObject connector = pagObj.Drop(connectorMaster, 0, 0) connector.Cells("BeginX").GlueTo(shpObj1.Cells("PinX")) connector.Cells("EndX").GlueTo(shpObj2.Cells("PinX")) doc.SaveAs(r'e:\temp\MyDrawing.vsd') doc.Close() appVisio.Visible =0 appVisio.Quit()
Comments