I had two problems. The first problem was inserting a sheet at a given position. The second problem was moving a sheet around. Since I mostly deal with the newer Excel file xlsx
, then I would be using openpyxl.
Various sources indicate new sheets are added to the end. I expected I would need to do this each time, and then move the sheet. I asked the question "(How to) move a worksheet..." thinking this was would solve both problems.
Ultimately, the first problem was easy once I finally found an example which showed workbook.create_sheet()
method takes an optional index
argument to insert a new sheet at a given zero-indexed position. (I really have to learn to look at the code, because the answer was here):
def create_sheet(self, title=None, index=None):
"""Create a worksheet (at an optional index)
[...]
Next. Turns out you can move a sheet by reordering the Workbook container _sheets
. So I made a little helper func to test the idea:
def neworder(shlist, tpos = 3):
"""Takes a list of ints, and inserts the last int, to tpos location (0-index)"""
lst = []
lpos = (len(shlist) - 1)
print("Before:", [x for x in range(len(shlist))])
# Just a counter
for x in range(len(shlist)):
if x > (tpos - 1) and x != tpos:
lst.append(x-1)
elif x == tpos:
lst.append(lpos)
else:
lst.append(x)
return lst
# Get the sheets in workbook
currentorder = wb.sheetnames
# move the last sheet to location `tpos`
myorder = neworder(currentorder)
>>>Before: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
>>>After : [0, 1, 2, 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
# get each object instance from wb._sheets, and replace
wb._sheets = [wb._sheets[i] for i in myorder]
The first answer was not hard to spot in the openpyxl documentation once I realized what it did. Just a bit surprised more blogs didn't mention moving sheets around.