Skip to content Skip to sidebar Skip to footer

How Can I Sort Excel Sheets/tabs In Workbook Using Openpyxl

I need to sort the tabs/sheets in a workbook alpha- numerically. I am using openpyxl to manipulate the worksheet.

Solution 1:

You can try to sort the workbook._sheets list.

workbook._sheets = sorted(workbook._sheets)

This may result in the active worksheet (referred to by an index) to change silently so the sorting operation should be followed by something like workbook.active = 0.

I would try it first with test data as the direct access to the so-called "private" _sheets attribute might mess things up and corrupt your data.

As per the comment by Charlie Clark below, using so-called "private" attributes can compromise the way a module is working. If you want to make it proper read the source thoroughly to understand what it involves and subclass the Workbook class to add a new method that does the sorting.

... and bear in mind that updating openpyxl might result in your finely crafted subclass not working anymore. You may suggest to include the sorting method into the openpyxl code so that it is maintained adequately.

Python will not forbid you to turn your computer into a disobedient monster as long as it is what you fancy.

We are all consenting adults here.

Guido von Rossum

Post a Comment for "How Can I Sort Excel Sheets/tabs In Workbook Using Openpyxl"