inserting a formula into a range of cells

79 views
Skip to first unread message

jhc

unread,
Nov 10, 2010, 6:55:28 PM11/10/10
to python-excel
I'd like to insert a formula into a range of cells. So if I was just
in Excel I would type the formula in, then 'copy down' in the
remaining cells.

Is there a way to do this in Python?

I'm just a newbie - I didn't even know any of this was possible before
this week. So please give me an example that I can use.

I was hoping something along the lines of cell A2 = B2 /
myVariableOrConstant

thanks in advance

John Machin

unread,
Nov 10, 2010, 8:45:34 PM11/10/10
to python...@googlegroups.com

Inserting cells into an existing workbook, or into a workbook on the fly
as you create it?

In the latter case, you need know only about xlwt (which creates XLS
files, including the formula functionality). In the former case you also
need to know about xlrd (reads XLS files) and xlutils (whose utilities
including copying/filtering XLS files).

See the tutorial that you can access via http://www.python-excel.org.

The formula examples in the tutorial don't cover the "copy down"
scenario. Here's an example with numbers in col A and you want a running
total in col B:

[preliminaries omitted; rows and columns are enumerated starting from
zero (A1 is (rowx=0, colx=0)); see tutorial]

sheet.write(1, 1, Formula('A2'), a_style)
cum_fmla_fmt = 'B%d + A%d'
for row_index in xrange(2, whatever):
fmla = Formula(cum_fmla_fmt % (row_index, row_index + 1))
sheet.write(row_index, 1, fmla, a_style)

Cheers,
John

Reply all
Reply to author
Forward
0 new messages