** Using Excel in Python
:PROPERTIES:
:categories: programming
:tags: excel
:date: 2013/04/06 14:01:02
:updated: 2013/04/06 14:01:02
:END:
There may be a time where you have an Excel sheet that already has a model built into it, and you normally change cells in the sheet, and it solves the model. It can be tedious to do that a lot, and we can use python to do that. Python has a COM interface that can communicate with Excel (and many other windows programs. see http://my.safaribooksonline.com/1565926218 for Python Programming on Win32). In this example, we will use a very simple Excel sheet that calculates the volume of a CSTR that runs a zeroth order reaction ($-r_A = k$) for a particular conversion. You set the conversion in the cell B1, and the volume is automatically computed in cell B6. We simply need to set the value of B1, and get the value of B6 for a range of different conversion values. In this example, the volume is returned in Liters.
#+BEGIN_SRC python
import win32com.client as win32
excel = win32.Dispatch('Excel.Application')
wb = excel.Workbooks.Open('c:/Users/jkitchin/Dropbox/pycse/data/cstr-zeroth-order.xlsx')
ws = wb.Worksheets('Sheet1')
X = [0.1, 0.5, 0.9]
for x in X:
ws.Range("B1").Value = x
V = ws.Range("B6").Value
print 'at X = {0} V = {1:1.2f} L'.format(x, V)
# we tell Excel the workbook is saved, even though it is not, so it
# will quit without asking us to save.
excel.ActiveWorkbook.Saved = True
excel.Application.Quit()
#+END_SRC
#+RESULTS:
: at X = 0.1 V = 22.73 L
: at X = 0.5 V = 113.64 L
: at X = 0.9 V = 204.55 L
This was a simple example (one that did not actually need Excel at all) that illustrates the feasibility of communicating with Excel via a COM interface.