openpyxl FORMULAE
时间: 2023-09-07 14:16:57 浏览: 141
homebrew-formulae
openpyxl is a Python library that allows you to work with Excel files. It provides functionality to read, write, and modify Excel files. When it comes to formulas in Excel files, openpyxl supports handling formulas through the `openpyxl.formula` module.
To access and manipulate formulas in openpyxl, you can use the `cell` object's `value` attribute. Here's an example of how you can set a formula in a cell using openpyxl:
```python
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.formula import Tokenizer
# Create a new workbook
wb = Workbook()
ws = wb.active
# Set a formula in cell A1
ws['A1'].value = '=SUM(B1:C1)'
# Get the formula from cell A1
formula = ws['A1'].value
# Parse the formula using Tokenizer
tokenizer = Tokenizer(formula)
parsed_formula = tokenizer.items
# Print the parsed formula
for item in parsed_formula:
print(item)
# Save the workbook
wb.save('example.xlsx')
```
In this example, we set a formula `=SUM(B1:C1)` in cell A1. We then retrieve the formula from cell A1 and parse it using `Tokenizer`. The parsed formula is then printed to the console.
Note that openpyxl does not evaluate formulas automatically. To calculate the results of the formulas, you can use other libraries like `xlwings` or `pandas`.
阅读全文