44

We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.

So, my question is twofold:

  • What is the best library to use to drive excel from python in such fashion?

  • Where's the best documentation/examples on using said library?

Cheers, /YGA

YGA
  • 9,546
  • 15
  • 47
  • 50
  • 1
    Check out Resolver One (http://www.resolversystems.com/products/, a Python-programmable spreadsheet. There is a free version for personal, non-commercial use available at http://www.resolversystems.com/download/. – codeape Jan 15 '09 at 07:49
  • 1
    Why hasn't anyone mentioned xlrd/xlwt/xlutils? www.python-excel.org – caps Jan 22 '15 at 15:51
  • @caps `xlrd/xlwt/xlutils` has severe limitations. To edit an existing excel, you must use`xlutils` to copy a read-only `xlrd.Book` to a writable `xlwt.Workbook`. A lot of things will be lost during the copy. According to its javadoc, it only `preserving as much information from the source object as possible.`, which makes it off my list. – smwikipedia Jan 04 '16 at 08:56

7 Answers7

49

For controlling Excel, use pywin32, like @igowen suggests.

Note that it is possible to use static dispatch. Use makepy.py from the pywin32 project to create a python module with the python wrappers. Using the generated wrappers simplifies development, since for instance ipython gives you tab completion and help during development.

Static dispatch example:

x:> makepy.py "Microsoft Excel 11.0 Object Library"
...
Generating...
Importing module
x:> ipython
> from win32com.client import Dispatch
> excel = Dispatch("Excel.Application")
> wb = excel.Workbooks.Append()
> range = wb.Sheets[0].Range("A1")
> range.[Press Tab]
range.Activate                 range.Merge
range.AddComment               range.NavigateArrow
range.AdvancedFilter           range.NoteText
...
range.GetOffset                range.__repr__
range.GetResize                range.__setattr__
range.GetValue                 range.__str__
range.Get_Default              range.__unicode__
range.GoalSeek                 range._get_good_object_
range.Group                    range._get_good_single_object_
range.Insert                   range._oleobj_
range.InsertIndent             range._prop_map_get_
range.Item                     range._prop_map_put_
range.Justify                  range.coclass_clsid
range.ListNames                range.__class__
> range.Value = 32
...

Documentation links:

codeape
  • 97,830
  • 24
  • 159
  • 188
22

I've done this by using pywin32. It's not a particularly pleasant experience, since there's not really any abstraction; it's like using VBA, but with python syntax. You can't rely on docstrings, so you'll want to have the MSDN Excel reference handy (http://msdn.microsoft.com/en-us/library/aa220733.aspx is what I used, if I remember correctly. You should be able to find the Excel 2007 docs if you dig around a bit.).

See here for a simple example.

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

Good luck!

brownan
  • 48
  • 4
igowen
  • 641
  • 4
  • 8
  • 8
    Check out my new project at http://xlwings.org that wraps this approach into an easy and Pythonic interface and provides possibilities to call it through Excel. – Felix Zumstein Jul 03 '14 at 12:51
8

Check out the DataNitro project (previous name IronSpread). It is a Python plug-in for Excel.

codeape
  • 97,830
  • 24
  • 159
  • 188
1

I wrote python class that allows working with Excel via COM interface in Windows http://sourceforge.net/projects/excelcomforpython/

The class uses win32com to interact with Excel. You can use class directly or use it as example. A lot of options implemented like array formulas, conditional formatting, charts etc.

Alex
  • 2,009
  • 6
  • 24
  • 27
1

I've spent about a week, and here's my implementation (or rather proof-of-concept): https://github.com/Winand/SimplePython

Main idea is to make Python code as easy to write and call from Microsoft Office as VBA macros (i've made Add-In only for Excel).

  • Client-server architecture (over TCP), so Python is started only once
  • Server is auto-started if it's not running
  • Server auto-reloads macro modules when user changes them
  • Easy-to-use control interface on Office ribbon
Winand
  • 2,093
  • 3
  • 28
  • 48
1

I worked on a home project last year that involves a client written as a Python Excel plug-in. The project is essentially an online database simplified for end-user access. The Excel plug-in allows users to query data out of the database to display in Excel.

I never got very far with the Excel plug-in and my code for it is a bit ugly. But, what I do have is under a BSD license and available via Bazaar at

http://www.launchpad.net/analyz/trunk

The client won't work since I don't have a public server running right now, but at least you can look at what I did with the code to get some ideas how this could work. The code will also show you how to build an MFC dialog in 100% Python.

user229044
  • 232,980
  • 40
  • 330
  • 338
Clint Miller
  • 15,173
  • 4
  • 37
  • 39
0

There is an interesting project for integrating python into excel as an in-process DLL which can be fount at:

http://opentradingsystem.com/PythonForExcel/main.html

Another somewhat more simple project along the same idea exists at:

http://www.codeproject.com/Articles/639887/Calling-Python-code-from-Excel-with-ExcelPython

These projects seem to have a lot of promise but need more development.