python - 使用 openpyxl 或 xl* 或 xlsxwriter 在工作簿中移动工作表?
问题描述
我已经阅读了openpyxl 、 xlwt、xlrd、xlutils、xlsxwriter的文档。我找不到在Excel 工作簿中移动工作表的方法。测试在末尾添加了一个工作表。
具体来说,我有一个各种各样的日历,['JAN','FEB',...,'DEC']
我需要根据需要更换月份。
如果不移动Excel 工作簿中的工作表,如何对其进行排序?您可以在指定工作表之后或之前插入工作表吗?
我只能找到一篇关于 SO用途win32com
和的帖子Book.Worksheets.Add(After=Sheet)
;似乎很奇怪,这些模块都没有这种方法。
默认似乎在工作簿末尾添加工作表。我可以复制目标文件,直到到达更新的工作表,插入新工作表,然后将原始副本继续到最后。(受这篇文章的启发)
解决方案
我有两个问题。第一个问题是在给定位置插入一张纸。第二个问题是移动一张纸。由于我主要处理较新的 Excel 文件xlsx
,因此我将使用 openpyxl。
各种消息来源表明新的工作表被添加到最后。我预计我每次都需要这样做,然后移动工作表。我问了“(如何)移动工作表......”这个问题,认为这可以解决这两个问题。
最终,第一个问题很容易,一旦我终于找到了一个示例,该示例显示workbook.create_sheet()
方法采用可选index
参数在给定的零索引位置插入新工作表。(我真的要学会看代码,因为答案就在这里):
def create_sheet(self, title=None, index=None):
"""Create a worksheet (at an optional index)
[...]
下一个。事实证明,您可以通过重新排序 Workbook container 来移动工作表_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 文档中不难发现。只是有点惊讶更多的博客没有提到移动床单。
推荐阅读
- wordpress - 在移动菜单上对齐最后 3 个菜单项
- java - 服务器从java中的另一个客户端发送事件?
- python - 如何从具有熊猫系列对象和浮点数的列表中删除浮点值
- google-apps-script - 如果选中复选框,则删除部分行
- inheritance - Kotlin 中的主构造函数 + 调用超级构造函数
- multidimensional-array - 有没有办法将表单中的所有字段收集到二维数组中以写入 Google 表格?
- visual-studio-code - Visual Studio graphql“执行查询”如何工作?
- spring - 根据枚举值选择验证
- python - ImportError:DLL 加载失败:找不到指定的模块。(NASA Fortran CEA 的 Python Rocketcea 包装器)
- python - 尝试打开文件时 TKinter 窗口“无响应”