Skip to content
Home » openpyxl Part 10 – Freezing Rows and Columns

openpyxl Part 10 – Freezing Rows and Columns

Spread the love

In the previous part of the openpyxl series we were adding and removing sheets. We didn’t save the changes, though, so the workbook remained unchanged. Today we’ll be talking about freezing rows and columns. This is what we do if our workbook is too large to see all the data at once, but still we want to see some data, like a particular row or column, even when we scroll it horizontally or vertically. We’ll be still working on the wb2.xlsx spreadsheet. Although it’s not too large to be see all at once, we can still use it to demonstrate how freezing rows and columns works.

Here’s the data our workbook contains:

companycitycategoryincomenumber_of_employees
Roses and PansiesTorontogardening456845.0026
Reader’s ParadiseSydneypublisher911500.0044
Dogs and CatsMadridpets458784.0036
Enjoy Your MealNew Orleansrestaurant447884.0018
Bloom StoreLondongardening1254654.0084
Tastes of the SouthMiamirestaurant587454.0042
Pets for EveryoneAthenspets987887.0021
Eat ‘Em UpHelsinkirestaurant1254477.0053
Mr. BunnyViennapets254478.0012
Bookworms RuleRomepublisher12447440

As usual, let’s start by loading the workbook:

>>> from openpyxl import load_workbook
>>> workbook = load_workbook(filename="wb2.xlsx")
>>> sheet = workbook.active

To freeze a row or column, we use the freeze_panes attribute. We set it to the first cell that is not supposed to be frozen. So, in our example we want to freeze the first row, which is the one with the headings, and the first column, which is the one with the company names. So, the first column that should not be frozen is B and the first row that should not be frozen is 2, so we must set the freeze_panes attribute to ‘B2’. This time I’m going to save the workbook so that we can then open it and see how it works. Here’s the code:

>>> sheet.freeze_panes = 'B2'
>>> workbook.save('wb2.xlsx')

Now let’s open the wb2.xlsx file and try scrolling the sheet both horizontally and vertically:

workbook

As you can see, the first row and the first column are not scrolled and remain always visible.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply