我有两个问题。第一个问题是在给定位置插入一张纸。第二个问题是移动一张纸。由于我主要处理较新的 Excel 文件 xlsx,所以我将使用 openpyxl。
各种消息来源表明新工作表已添加到末尾。我预计我每次都需要这样做,然后移动工作表。我问了“(如何)移动工作表......”这个问题,我认为这可以解决这两个问题。
最终,第一个问题很容易,一旦我终于找到了一个示例,该示例显示workbook.create_sheet() 方法采用可选的index 参数在给定的零索引位置插入新工作表。 (我真的要学会看代码,因为answer was here):
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 文档中不难发现。有点惊讶的是,更多的博客没有提到移动床单。