Python openpyxl – Write formula to cell

In this post we will be creating a Python script that will write a formula to a cell using the openpyxl library. Openpyxl is a library that allows us to interact with Excel files in Python. It provides a range of tools for reading, writing, manipulating, and formatting Excel data. This makes it a useful tool for data analysis and reporting tasks.

See the sample of Python code below where we use the openpyxl library to write a formula to a cell. We start by loading an existing Excel file called example.xlsx and assign it to a variable named workbook. We then retrieve the active worksheet from the workbook, this is the worksheet displayed when the Excel file is opened. Next we then set the values of cells A1 and B1 to 10 and 8, respectively. A formula is also set for cell C1 which adds the values of cells A1 and B1. Finally the changes made to the Excel file are saved using the save() method.

import openpyxl

workbook = openpyxl.load_workbook('example.xlsx')

worksheet = workbook.active

worksheet['A1'] = 10
worksheet['B1'] = 8

worksheet['C1'] = '=A1+B1'

workbook.save('example.xlsx')

See below a screenshot of what our resulting worksheet looks like.

Python openpyxl - Write formula to cell

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply