# Python Write Excel xlsx File with Formula Cells using OpenPyXL

In this Python openpyxl tutorial we learn how to write Excel xlsx files with formula cells using the openpyxl package.

#### How to install the openpyxl package

To install the openpyxl package using the command below.

`pip install openpyxl`

#### Step by step to write Excel xlsx file with formula

Import the Workbook from the openpyxl package.

`from openpyxl import Workbook`

Create a new Workbook object.

`workbook = Workbook()`

Get the default Worksheet object.

`worksheet = workbook.active`

Assign values for cell A1, A2, A3.

```
worksheet['A1'] = 10
worksheet['A2'] = 5
worksheet['A3'] = 7
```

Assign formula to cell A4 as sum values from A1 to A3.

`worksheet['A4'] = '=SUM(A1:A3)'`

Save the Workbook as formula.xlsx file.

`workbook.save('formula.xlsx')`

The complete Python program as below.

write_excel_file_formula.py

```
from openpyxl import Workbook
workbook = Workbook()
worksheet = workbook.active
worksheet['A1'] = 10
worksheet['A2'] = 5
worksheet['A3'] = 7
worksheet['A4'] = '=SUM(A1:A3)'
workbook.save('formula.xlsx')
```

Execute the above Python program we will get the Excel file formula.xlsx as below screenshot.

Happy Coding ðŸ˜Š