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

5
我想使用openpyxl将一个单元格的公式复制到另一个单元格,并获得您通常在Excel中使用的转置。
例如,将公式=SUM(J3:J18)从一个单元格复制到下一列时,会自动更改为=SUM(K3:K18)
我找到了一种使用win32com.client的方法,但我不知道是否有openpyxl的等效方法。
是否有一种使用openpyxl的方法来实现这一点,或者我需要使用正则表达式手动替换所有列号?
谢谢。
3个回答

5
openpyxl 提供了一些工具来通过 Translator 类翻译公式。在与公式相关的页面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).

    """

2
你需要手动完成这项任务,但你可以考虑使用tokeniser而不是编写自己的解析器。

0
我认为Jean Francois T.已经提供了正确的答案,该答案源自openpyxl文档。
以下方法明确了如何使用参数。此外,它更通用,因为它不需要字面值,因此在循环内实用。
假设您想将公式从源单元格向右复制到目标单元格的下一列:
from openpyxl.formula.translate import Translator
source_cell = ws.cell(row=r, column=c)
dest_cell = ws.cell(row=r, column=c+1) # one column to the right
formula = source_cell.value
translated = Translator(formula, source_cell.coordinate).translate_formula(dest_cell.coordinate)
ws[dest_cell.coordinate] = translated

在文档示例中,如果你考虑行索引为r=2,列索引(对于F)为c=6,但也可以很容易地成为循环的迭代变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接