我有两个问题。第一个问题是在给定位置插入一张纸。第二个问题是移动一张纸。因为我主要处理较新的 Excel 文件xlsx
,那么我将使用 openpyxl。
各种消息来源表明新的工作表被添加到末尾。我预计每次都需要这样做,然后移动纸张。我问了这个问题“(如何)移动工作表......”认为这可以解决这两个问题。
最终,一旦我终于找到了一个显示的示例,第一个问题就很容易了workbook.create_sheet()
方法需要一个可选的index
在给定的零索引位置插入新工作表的参数。 (我真的要学会看代码,因为答案就在这里):
def create_sheet(self, title=None, index=None):
"""Create a worksheet (at an optional index)
[...]
下一个。事实证明,您可以通过重新排序工作簿容器来移动工作表_sheets
。所以我做了一个小辅助函数来测试这个想法:
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]
一旦我意识到它的作用,第一个答案就不难在 openpyxl 文档中找到。只是有点惊讶更多的博客没有提到移动床单。