Openpyxl 1.8.5: Reading the result of a formula typed in a cell using openpyxl

后端 未结 4 700
刺人心
刺人心 2020-11-30 11:21

I am printing some formula in one of the Excel sheets:

wsOld.cell(row = 1, column = 1).value = \"=B3=B4\"

But I cannot use its result in im

4条回答
  •  再見小時候
    2020-11-30 11:40

    xlwings, PyXll FlyingKoala, DataNitro all use Excel as the interface to using Python.

    If you want to use a Python library you can try PyCel, xlcalculator, Formulas and Schedula.

    I am the project owner of xlcalculator.

    xlcalculator uses openpyxl to read Excel files and adds functionality which translates Excel formulas into Python.

    An example using xlcalculator with an Excel file:

    from xlcalculator import ModelCompiler
    from xlcalculator import Model
    from xlcalculator import Evaluator
    
    filename = r'use_case_01.xlsm'
    compiler = ModelCompiler()
    new_model = compiler.read_and_parse_archive(filename)
    evaluator = Evaluator(new_model)
    val1 = evaluator.evaluate('First!A2')
    print("value 'evaluated' for First!A2:", val1)
    

    An example using xlcalculator with a dict;

    input_dict = {
        "B4": 0.95,
        "B2": 1000,
        "B19": 0.001,
        "B20": 4,
        # B21
        "B22": 1,
        "B23": 2,
        "B24": 3,
        "B25": "=B2*B4",
        "B26": 5,
        "B27": 6,
        "B28": "=B19*B20*B22",
        "C22": "=SUM(B22:B28)",
      }
    
    from xlcalculator import ModelCompiler
    from xlcalculator import Model
    from xlcalculator import Evaluator
    
    compiler = ModelCompiler()
    my_model = compiler.read_and_parse_dict(input_dict)
    evaluator = Evaluator(my_model)
    
    for formula in my_model.formulae:
        print("Formula", formula, "evaluates to", evaluator.evaluate(formula))
    
    # cells need a sheet and Sheet1 is default.
    evaluator.set_cell_value("Sheet1!B22", 100)
    print("Formula B28 now evaluates to", evaluator.evaluate("Sheet1!B28"))
    print("Formula C22 now evaluates to", evaluator.evaluate("Sheet1!C22"))
    

提交回复
热议问题