Calculating formulae in Excel with Python

拈花ヽ惹草 提交于 2019-12-10 11:44:36

问题


I would like to insert a calculation in Excel using Python. Generally it can be done by inserting a formula string into the relevant cell. However, if i need to calculate a formula multiple times for the whole column the formula must be updated for each individual cell. For example, if i need to calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k). In excel it is possible to calculate C1=A1+B1 and then automatically expand the calculation by dragging the mouse from C1 downwards. My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?

Thank you in advance, Sasha


回答1:


As Roberto mentions, you can use xlwt and a trusty for-loop:

import xlwt

w = xlwt.Workbook()
ws = w.add_sheet('mysheet')

for i in range(10):
    ws.write(i, 0, i)
    ws.write(i, 1, i+1)
    ws.write(i, 2, xlwt.Formula("$A$%d+$B$%d" % (i+1, i+1)))

w.save('myworkbook.xls')



回答2:


If you are using COM bindings, then you can simply record a macro in Excel, then translate it into Python code.
If you are using xlwt, you have to resort to normal loops in python..




回答3:


Sasha,

Python code translated from your macro would look like this:

startCell = mySheet.Range("M6")
wholeRange = mySheet.Range("M6:M592")
startCell.FormulaR1C1 = "=R[-1]C[-7]/RC[-10]*R[-1]C"
startCell.AutoFill(Destination=wholeRange)

Haven't tested it, but I write this often at work. Let me know if it doesn't work.




回答4:


If you want to iterate in the horizontal direction, here is a function I use. 0 -> a, 26 -> aa, 723 -> aav

def _num_to_let(num):
        if num > 25:
            return _num_to_let(num/26-1) + chr(97+ num % 26)
        return chr(97+num)



回答5:


If you want to iterate in xlwt for columns (in formulas) you can use Utils module from xlwt like this:

from xlwt import Utils
print Utils.rowcol_pair_to_cellrange(2,2,12,2)
print Utils.rowcol_to_cell(13,2)
>>>
C3:C13
C14


来源:https://stackoverflow.com/questions/1116725/calculating-formulae-in-excel-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!