复制到特定工作表:openpyxl-使用copy_worksheet时忽略目标工作表

时间:2018-07-02 00:48:16

标签: excel python-3.x openpyxl

对于此answerthese documents,我尝试指定要写入的$.get(url, function(result){ $('mydialogdiv').html(result); }); source工作表,但是当我这样做时,结果与尚未指定目标:

target

vs

from openpyxl import load_workbook 
wb = load_workbook('MyFile.xlsx')
ws = 'Sheet1'


idx = book.index(ws)
new_ws = 'Test'
book.create_sheet(new_ws, idx+1)
source = book[ws]
target = book[new_ws]
target = book.copy_worksheet(source)
wb.save('Output.xlsx')

这两个操作都会在工作簿的末尾添加一个名为source = book[ws] book.copy_worksheet(source) wb.save('Output.xlsx') 的新工作表。 如何将工作表复制到另一个空白工作表或工作簿中的特定位置?

2 个答案:

答案 0 :(得分:1)

# new copied sheet was assigned to target
target = wb.copy_worksheet(wb.source_sheet)

# now just change the name to desired one
target.title = desired_name

答案 1 :(得分:-1)

我仍然不确定copy_workbook写入源代码是否存在错误。但是,这是我为解决此限制而编写的代码:

from openpyxl import load_workbook

wb = load_workbook('MyFile.xlsx')
ws = 'Sheet1'
ws_new_name = 'original_sheet'
new_ws = 'Test'

idx = wb.index(ws)
#print (ws.title, 'index is',  idx)

wb.copy_worksheet(wb[ws.title])

#Get the position of the new sheet
n = len(wb.sheetnames) #number of worksheets
copied_ws = wb.worksheets[n-1]
# print ('Final sheet is:', wb.sheetnames[n-1])

#rename worksheets
copied_ws.title = new_ws
ws.title = ws_new_name

#reorder the sheet
sheetorder = [i for i in range(n)] #create an array equal to number of worksheets
for j in range(n-1-idx): #shift sheet order after copied sheet by 1
    sheetorder[j+idx+1] =  sheetorder[j+idx+1]-1
sheetorder[idx+1] = n-1 #last sheet gets inserted directly after copied sheet
wb._sheets =[wb._sheets[i] for i in sheetorder]