10.07.2015 Views

Automate Microsoft Office with Python - Mil-OSS

Automate Microsoft Office with Python - Mil-OSS

Automate Microsoft Office with Python - Mil-OSS

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Why?• In an <strong>OSS</strong> Conference - why even discuss <strong>Microsoft</strong><strong>Office</strong>?• Interoperability• Practicality• Capabilities• If using <strong>Microsoft</strong> <strong>Office</strong> – why even discussautomation <strong>with</strong> non-<strong>Office</strong> tools?• Capabilities• Integration• Future-proofing• Best practices (separation of code and data)• Ideological (one step closer to software freedom)GTRI_B-‹#›


How?• Tools to be demonstrated• <strong>Python</strong>• Cpython – standard <strong>Python</strong> interpreter• Iron<strong>Python</strong> - .Net <strong>Python</strong> interpreter• Libraries• pywin32 - Win32Com, Win32API• pyodbc – SQL database handler• xlrd – Excel file reader• Utilities• ipythonGTRI_B-‹#›


<strong>Python</strong> Flavors• C<strong>Python</strong>• Currently, the reference implementation for the <strong>Python</strong> language• Interfaces well <strong>with</strong> C extensions• Jython• Java-based implementation• Provides simple access to Java libraries• Iron<strong>Python</strong>• .NET framework implementation• Surprisingly good performance• PyPy• <strong>Python</strong> written in <strong>Python</strong>• Very good Just-In-Time (JIT) compiler• Could be the future of <strong>Python</strong>GTRI_B-‹#›


General Approach• pywin32 (Win32Com, Win32API)• Developed by Mark Hammond• <strong>Python</strong> Programming on Win32import win32com.cliento = win32com.client.Dispatch("Object.Name")# or o = win32com.client.gencache.EnsureDispatch("Object.Name")o.Method()o.property = "New Value"print o.propertyGTRI_B-‹#›


Powerpoint AutomationGTRI_B-‹#›


Powerpoint Automation (How?)• ipython – interactive interpreter• very popular in scientific processing• hooks for remote display of results• Custom code• attaches to ipython session• pulls line- and image-oriented data from ipython• queries Powerpoint presentation for current slide• locates objects <strong>with</strong> specific alt-text• modifies objects for proper displayGTRI_B-‹#›


Outlook Automation• Developed Dialer Application• Needed contact info from Outlookimport win32com.clientoutlook_app = win32com.client.gencache.EnsureDispatch("Outlook.Application")mapi = outlook_app.GetNamespace("MAPI")contacts = mapi.GetDefaultFolder(win32com.client.constants.olFolderContacts)print ‘number of contacts=‘, len(contacts.Items)for index in range(len(contacts.Items)):contact = contacts.Items.Item(index + 1)GTRI_B-‹#›


Word Automationimport win32com.client# launch or connect to <strong>Microsoft</strong> Word.word_app = win32com.client.Dispatch("Word.Application")word_app.Visible = True92 Lorem86 Sed fa103 Curabi101 Nulla113 Sed codoc = word_app.ActiveDocument# iterate through the paragraphsfor para in doc.Paragraphs:range = para.Rangeprint '%3d %s' % (range.Words.Count, range.Text[0:6])GTRI_B-‹#›


Excel Automation• Lots of options• COM• ODBC• export as CSV, HTML• If using Excel file in read-onlymode, consider xlrd library.• Extract data from Excel spreadsheets (.xls and.xlsx, versions 2.0 onwards) on any platform.Pure <strong>Python</strong> (2.6 to 2.7). Strong support forExcel dates. Unicode-aware.import xlrdbook = xlrd.open_workbook(SOME_EXCEL_FILE_NAME)sheet = book.sheet_by_index(0) # first sheet# iterate row-by-rowfor row in range(sheet.nrows):# grab a single cellcell = sheet.cell_value(row, SOME_COLUMN_INDEX)GTRI_B-‹#›


Access Automation• Simplest approach• install pyodbc library• treat Access file as normal SQL databasefrom pyodbc import connectfn = path_to_access_mdb_filedb = connect(r'DRIVER={<strong>Microsoft</strong> Access Driver (*.mdb, *.accdb)};DBQ=%s' % fn )cursor = db.cursor()cursor.execute(SOME_SQL_QUERY)for row in cursor.fetchall():blah ...GTRI_B-‹#›


Visio Automation (PyWin32)import win32com.clientfrom win32com.client import constantswin32com.client.gencache.EnsureDispatch("Visio.Application")visapp = win32com.client.Dispatch("Visio.Application")doc = visapp.Documents.Add("")page = visapp.ActivePagestencilname = "basic_u.vss"stencildocflags = constants.visOpenRO | constants.visOpenDockedstencildoc = visapp.Documents.OpenEx(stencilname , stencildocflags )masterrect = stencildoc.Masters.ItemU("rectangle")mastercircle = stencildoc.Masters.ItemU("circle")masterconnector= stencildoc.Masters.ItemU("dynamic connector")shape1 = page.Drop(masterrect, 1,1)for i in range(3):shape2 = page.Drop(mastercircle, 3+2*i,3+2*i)connector = page.Drop(masterconnector, -1,-1)connector.CellsU("BeginX").GlueTo(shape1.CellsSRC(1, 1, 0))connector.CellsU("EndY").GlueTo(shape2.CellsSRC(1, 1, 0))shape1 = shape2GTRI_B-‹#›


Visio Automation (Iron<strong>Python</strong>)import clrclr.AddReference("<strong>Microsoft</strong>.<strong>Office</strong>.Interop.Visio")import <strong>Microsoft</strong>.<strong>Office</strong>.Interop.Visio as IVisiovisapp = IVisio.ApplicationClass()doc = visapp.Documents.Add("")page = visapp.ActivePagestencilname = "basic_u.vss"stencildocflags = IVisio.VisOpenSaveArgs.visOpenRO | IVisio.VisOpenSaveArgs.visOpenDockedstencildoc = visapp.Documents.OpenEx(stencilname , stencildocflags )masterrect = stencildoc.Masters.ItemU("rectangle")mastercircle = stencildoc.Masters.ItemU("circle")masterconnector= stencildoc.Masters.ItemU("dynamic connector")shape1 = page.Drop(masterrect, 1,1)for i in range(3):shape2 = page.Drop(mastercircle, 3+2*i,3+2*i)connector = page.Drop(masterconnector, -1,-1)connector.CellsU("BeginX").GlueTo(shape1.CellsSRC(1, 1, 0))connector.CellsU("EndY").GlueTo(shape2.CellsSRC(1, 1, 0))shape1 = shape2GTRI_B-‹#›


Resource GuideStandard <strong>Python</strong>(C<strong>Python</strong>)Iron<strong>Python</strong> (alternative<strong>Python</strong> interpreter for<strong>Microsoft</strong> .Netenvironment)Win32Com and Win32APIipythonxlrdhttp://python.orghttp://ironpython.nethttp://sourceforge.net/projects/pywin32/http://ipython.orghttp://pypi.python.org/pypi/xlrdpyodbchttp://code.google.com/p/pyodbc/GTRI_B-‹#›

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!