1

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

4

6 に答える 6

3

Robertoが言及しているように、xlwt と信頼できる for ループを使用できます

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')
于 2009-07-12T20:19:39.017 に答える
0

COMバインディングを使用している場合は、Excelでマクロを記録し、それをPythonコードに変換するだけです。
xlwtを使用している場合は、pythonの通常のループに頼る必要があります。

于 2009-07-12T20:02:31.110 に答える
0

列 (式) の xlwt で反復処理する場合は、次のように xlwt の Utils モジュールを使用できます。

from xlwt import Utils
print Utils.rowcol_pair_to_cellrange(2,2,12,2)
print Utils.rowcol_to_cell(13,2)
>>>
C3:C13
C14
于 2016-04-02T22:24:16.803 に答える
0

水平方向に繰り返したい場合は、私が使用する関数を次に示します。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)
于 2011-03-29T22:57:54.753 に答える
0

サーシャ、

マクロから変換された Python コードは次のようになります。

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

テストはしていませんが、職場で頻繁に書いています。うまくいかない場合はお知らせください。

于 2009-07-26T02:48:08.650 に答える