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

问题描述 投票:0回答:3

我想使用

openpyxl
以及使用 Excel 时通常得到的换位将公式从一个单元格复制粘贴到另一个单元格。

例如,将公式

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

我发现这种方法可以通过使用

win32com.client
来工作,但我不知道
openpyxl
的任何等效项。

有没有办法使用

openpyxl
来执行此操作,或者我应该使用正则表达式手动替换所有列号?

谢谢

python excel 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
,但很容易成为循环的迭代变量。

© www.soinside.com 2019 - 2024. All rights reserved.