How can I sort excel sheets/tabs in workbook using openpyxl

帅比萌擦擦* 提交于 2019-12-23 22:10:01

问题


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


回答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



来源:https://stackoverflow.com/questions/37681005/how-can-i-sort-excel-sheets-tabs-in-workbook-using-openpyxl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!