简体   繁体   中英

Copy formula from one cell to another using openpyxl

I would like to copy-paste the formula from one cell to another using openpyxl with the transposition you usually get when you use Excel.

For example, copying the formula =SUM(J3:J18) to the next column would automatically change it to =SUM(K3:K18) .

I found this method that could work by using win32com.client but I don't know any equivalent for openpyxl .

Is there a way to do this using openpyxl or shall I manually replace all the column numbers using regex?

Thanks

您将不得不手动执行此操作,但是您可能希望使用令牌处理程序,而不是编写自己的解析器。

openpyxl provides (at least now) some tools to translate formulae via the Translator class. It is mentionned in the page related to formulae tokenizer :

Here is an example on how to use it.

 >>> from openpyxl.formula.translate import Translator
 >>> ws['F2'] = "=SUM(B2:E2)"
 >>> # move the formula one colum to the right
 >>> ws['G2'] = Translator("=SUM(B2:E2)", "F2").translate_formula("G2")
 >>> ws['G2'].value
 '=SUM(C2:F2)'

Here is the current prototype of the function for translating formula:

def translate_formula(self, dest=None, row=None, col=None):
    """
    Convert the formula into A1 notation, or as row and column coordinates

    The formula is converted into A1 assuming it is assigned to the cell
    whose address is `dest` (no worksheet name).

    """

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM