In this post we will be creating a Python script that will rotate text within a cell in an existing 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 rotate the text within a cell in an existing Excel spreadsheet. The text within our cell will rotate by given number of degrees, this can range from 0° to 180°. We start by loading our existing Excel file called example.xlsx
and assign it to a variable named workbook
. Next we retrieve the active worksheet from the workbook.
We then select cell A1
in the worksheet
object, and set the Alignment
of that cell to have a textRotation
of 90
. (Clockwise)
We also select cell A
2 in the worksheet
object, and set the Alignment
of that cell to have a textRotation
of 45
. (Clockwise)
Finally the changes made to the Excel file are saved using the save()
method.
import openpyxl
from openpyxl.styles import Alignment
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook.active
worksheet['A1'].alignment = Alignment(textRotation=90)
worksheet['A2'].alignment = Alignment(textRotation=45)
workbook.save('example.xlsx')
See the image below as an example.

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