Python openpyxl – Indent text in cell

In this post we will be creating a Python script that will indent 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 indent the text within a cell in an existing Excel spreadsheet. Note that the number of spaces for indentation can defined for each cell if needed. 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 set the alignment options for cell A1 and A2. Here, indent is passed as a parameter to the Alignment constructor, which sets the left indent of the cell contents to 1 and 2 characters respectively. 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 =

worksheet['A1'].alignment = Alignment(indent=1)
worksheet['A2'].alignment = Alignment(indent=2)'example.xlsx')

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

Leave a Reply