In this post we will be creating a Python script that will change the font type of a cell within an Excel spreadsheet 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 change the font type of a cell within an Excel spreadsheet. We start by creating a new Excel workbook and assign it to a variable named workbook
. Next we retrieve the active worksheet from the workbook.
We then create a new Font object with the font type attribute set to the type we are wanting. Next we select cell A1
of the worksheet
and assign it to the variable cell
. The Font object defined earlier is assigned to our cell. Here we also add a value to our cell which is in this case ‘Hello world!’. Finally the changes made to the Excel file are saved using the save()
method.
import openpyxl
from openpyxl.styles import Font
workbook = openpyxl.Workbook()
worksheet = workbook.active
font = Font(name='Arial')
cell = worksheet['A1']
cell.font = font
cell.value = 'Hello, world!'
workbook.save('example.xlsx')
Take a look at some of our other content around the Python programming language by clicking here.