使用 openpyxl 将公式从一个单元格复制到另一个单元格

Copy formula from one cell to another using openpyxl

我想使用 openpyxl 将公式从一个单元格复制粘贴到另一个单元格,并使用 Excel.

时通常得到的换位

例如,将公式 =SUM(J3:J18) 复制到下一列会自动将其更改为 =SUM(K3:K18)

我发现这种方法可以通过使用 win32com.client 来工作,但我不知道 openpyxl 的任何等效方法。

有没有办法使用 openpyxl 来做到这一点,或者我是否应该使用正则表达式手动替换所有列号?

谢谢

您必须手动执行此操作,但您可能希望使用 tokeniser 而不是编写自己的解析器。

openpyxl 提供(至少现在)一些工具来通过 Translator class 翻译公式。在与公式相关的页面中提到 tokenizer:

这是一个如何使用它的例子。

 >>> 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)'

这是翻译公式的当前函数原型:

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).

    """