第三天 解析公式

openpyxl对单元格内的公式支持有限。openpyxl.formula包包含了一个 Tokenizer类,它可以将公式分割成构成该公式的token。用法如下:

from openpyxl.formula import Tokenizer

tok = Tokenizer("""=IF($A$1,"then True",MAX(DEFAULT_VAL,'Sheet 2'!B1))""")
print("\n".join("%12s%11s%9s" % (t.value, t.type, t.subtype) for t in tok.items))

运行结果
在这里插入图片描述如上所示,token有三个有意思的属性:

  • 值(value):公式子串产生的```token``

  • 类型(type):
      Token.LITERAL:当单元格不包含公式时,默认为常量
      Token.OPERAND:公式中的任意值
      Token.FUNC:函数调用被分解为多个token:opener,参数,closer;函数名和圆括号构成了一个FUNC token
      Token.ARRAY:由花括号构成{}构成
      …

  • 子类型:一些上述的类型使用子类型提供额外的信息

Translating formulae from one location to another

It is possible to translate (in the mathematical sense) formulae from one location to another using the openpyxl.formulas.translate.Translator class. For example, there a range of cells B2:E7 with a sum of each row in column F:

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)", origin="F2").translate_formula("G2")
ws['G2'].value=SUM(C2:F2)'

Note

This is limited to the same general restrictions of formulae: A1 cell-references only and no support for defined names.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值