[英]Move a worksheet in a workbook using openpyxl or xl* or 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 容器_sheets
來移動工作_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 文檔中找到。 只是有點驚訝更多的博客沒有提到移動床單。
這是我想出的(使用 openpyxl)
def move_sheet(wb, from_loc=None, to_loc=None):
sheets=wb._sheets
# if no from_loc given, assume last sheet
if from_loc is None:
from_loc = len(sheets) - 1
#if no to_loc given, assume first
if to_loc is None:
to_loc = 0
sheet = sheets.pop(from_loc)
sheets.insert(to_loc, sheet)
我的答案是床單的基本移動。 我在 openpyxl 中使用 move_sheets function
假設您有名為工作表 1:“abc”和工作表 2:“xyz”的工作表,並且您想將 xyz 從第二個 position 移動到第一個
import openpyxl as xl
wb = xl.load_worksheet("C:\\Users\\Desktop\\testfile.xlsx") #load worksheet using the excel file path, make sure you load the file from correct path
wb.active = 1 #the sheet index starts from 0 , hence 1 will select the second sheet ie xyz
wb.move_sheet(wb.active, offset = -1) #this will offset the current active sheet which is xyz be one position to the left which in our case is 1st position
wb.save(//path where you want to save the file.xlsx)
xtian解決方案的補充,可選擇將工作表從任何位置向前或向后移動到任何位置。
from pathlib import Path
from openpyxl import load_workbook
def neworder(file, fpos, tpos):
"""Takes a list of ints, and inserts the fpos (from position) int, to tpos (to position)"""
wb = load_workbook(filename=file)
shlist = wb.sheetnames # get current order sheets in workbook
lst = []
lpos = (len(shlist) - 1) # last position
if lpos >= fpos > tpos >= 0: # move from a high to low position
for x in range(lpos+1):
if x == tpos:
lst.append(fpos)
elif tpos < x <= fpos:
lst.append(x-1)
else:
lst.append(x)
if lpos >= tpos > fpos >= 0: # move from a low to high position
for x in range(lpos+1):
if x == tpos:
lst.append(fpos)
elif fpos <= x < tpos:
lst.append(x+1)
else:
lst.append(x)
wb._sheets = [wb._sheets[i] for i in lst] # get each object instance from wb._sheets, and replace
wb.save(filename=file)
return
filex = Path('C:/file.xlsx')
neworder(filex, 83, 12) # move worksheet in 83rd position to 12th position
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.